Javascript使用JSON.stringify()返回对象将对象属性转换为字符串

时间:2017-10-13 17:24:27

标签: javascript json string object

我有一个对象数组,如下所示:

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解析程序的字符串,但是在使用以下代码时:

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

检查typeof(item.response)我的数组中的某个项目后,仍然会返回object

但是,如果我在for循环之外手动设置单个项目的属性,它似乎按预期工作。

e.g。

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

1 个答案:

答案 0 :(得分:2)

当您使用for...in时,item是索引,而不是对象本身。而是使用for...of,将值分配给item



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);