如何迭代数组和字符串化属性

时间:2018-03-22 20:14:31

标签: javascript arrays sorting

我正在尝试累积数组的属性并将其作为字符串保存回数组,以便稍后使用JSON.parse进行解析。

在初始数据集中,items属性是一个数组。

我想重构数据,使得items是一串对象。

给出类似的东西:

[{
   {
     "n":"1",
     "items": [0: "{"id":"id1","desc":"description1"}",
               1: "{"id":"id2","desc":"description2"}"
               2: "{"id":"id3","desc":"description3"}"]
   },
   {
     "n":"2",
     "items": [0: "{"id":"id4","desc":"description4"}",
               1: "{"id":"id5","desc":"description5"}"
               2: "{"id":"id6","desc":"description6"}"]
   }
}]

转换为:

[{
   {
     "n":"1",
     "items": "[{"id":"id1","desc":"description1"}","{"id":"id2","desc":"description2"}","{"id":"id3","desc":"description3"}]"
   },
   {
     "n":"2",
     "items": "[{"id":"id4","desc":"description4"}","{"id":"id5","desc":"description5"}", "{"id":"id6","desc":"description6"}]"
   }
}]

2 个答案:

答案 0 :(得分:2)

我必须清理你的数据,所以我会假设我在下面设置的数据结构就是你的实际意思。



const data = [
  {
    "n":"1",
    "items": [
      {"id":"id1","desc":"description1"},
      {"id":"id2","desc":"description2"},
      {"id":"id3","desc":"description3"}
    ]
  },
  {
    "n":"2",
    "items": [
      {"id":"id4","desc":"description4"},
      {"id":"id5","desc":"description5"},
      {"id":"id6","desc":"description6"}
    ]
  }
];

const newData = data.map(val => {
  return Object.assign({}, val, {
    items: JSON.stringify(val.items)
  });
});

console.log(newData);




答案 1 :(得分:1)

  arr.map(({ items, ...rest }) => ({ items: JSON.stringify(items), ...rest }));