2017-10-13 3 views
0

を返すJSON.stringify()を使用して文字列にオブジェクトのプロパティを変換する私はそうのように、オブジェクトの配列を持っている:Javascriptがオブジェクト

var arr = [{request: {funding : 123, id: 123abc, membership: true}, 
response: {funding : 285, success: true }}, 
{request: {funding : 123, id: 123def, membership: true}, 
response: {funding : 167, success: true }}, 
{request: {funding : 123, id: 123def, membership: true}, 
response: {funding : 234, success: true }}] 

私はしかし、CSV解析プログラムのための文字列の中にネストされたオブジェクトを変換しようとしています次のコードを使用している場合:私の配列内のアイテムのためtypeof(item.response)をチェックした後

for (var item in arr) 
    { item.response = JSON.stringify(item.response); 
     item.request = JSON.stringify(item.request); 
} 

を、私はまだobjectを返します。

しかし、私は個々の項目のプロパティをforループの外側に手動で設定すると、意図したとおりに動作するように見えます。

arr[0].response = JSON.stringify(arr[0].response) 
typeof(arr[0].response) // string 

答えて

2

あなたがfor...initemを使用し、インデックスではなく、オブジェクトそのものです。代わりにitemに値を代入すること、for...ofを使用してください:あなたはあなたのデータを変異させたくない場合は

var arr = [{"request":{"funding":123,"id":"123abc","membership":true},"response":{"funding":285,"success":true}},{"request":{"funding":123,"id":"123def","membership":true},"response":{"funding":167,"success":true}},{"request":{"funding":123,"id":"123def","membership":true},"response":{"funding":234,"success":true}}]; 
 

 
for (var item of arr) { 
 
    item.response = JSON.stringify(item.response); 
 
    item.request = JSON.stringify(item.request); 
 
} 
 

 
console.log(arr);

は、Array#mapは新しいオブジェクトで、新しい配列を作成し、代わりに変えるでしょうオリジナル:

var arr = [{"request":{"funding":123,"id":"123abc","membership":true},"response":{"funding":285,"success":true}},{"request":{"funding":123,"id":"123def","membership":true},"response":{"funding":167,"success":true}},{"request":{"funding":123,"id":"123def","membership":true},"response":{"funding":234,"success":true}}]; 
 

 
var result = arr.map(function(item) { 
 
    return { 
 
    response: JSON.stringify(item.response), 
 
    request: JSON.stringify(item.request) 
 
    }; 
 
}); 
 

 
console.log(result);

+0

パーフェクト、ありがとう! – mburke05

+0

ようこそ。私が追加した他のオプションを見て、答えを受け入れることを忘れないでください:) –