将嵌套数组转换为js中的JSON字符串?

时间:2017-11-08 21:37:08

标签: javascript arrays json string angular

我有一组这样的数组:[["Sarah"],["Jamie"],["B"],["148"]]

我希望将其转换为 JSON字符串,并为每个vau提供特定元素。例如,

{ "name":"Sarah", "grade":"148", "School":"B"...}

我该怎么办?我试图toString数组然后绑定这个元素,但它不能很好地工作..

Original Json

   "Data":{
      "Table":[
         {
            "Name":[
               "Jamie"
            ],
            "School":[
               "A"
            ],
            "grade":[
               "99"
            ]

         },
         {
            "Name":[
               "Mike"
            ],
            "School":[
               "B"
            ],
            "grade":[
               "148"
            ]
         }
      ]
   }
}

3 个答案:

答案 0 :(得分:0)

You can use reduce to do this!

let newData = data.Data.Table.reduce(function(arr, obj) {
    let newObj = {};
    for (let key in obj) {
        newObj[key] = obj[key][0]
    }

    arr.push(newObj);
    return arr;
}, [])

Demo: https://jsfiddle.net/500eo2gp/

答案 1 :(得分:0)

let newDataArray = this.data.Data.Table.reduce(function(arr, obj) {
  let newObj = {};
  for (let key in obj) {
    newObj[key] = obj[key][0]
  }

  arr.push(newObj);
    return arr;
  }, []
);
newData =JSON.stringify(newDataArray);
来自tymeJV的代码片段中的

JSON.stringify(newDataArray)数组将为您提供如下的JSON字符串。

[{"Name":"Jamie","School":"A","grade":"99"},{"Name":"Mike","School":"B","grade":"148"}]

演示: http://plnkr.co/edit/wPhVTOFhRgERLXKCuoYl?p=preview

答案 2 :(得分:0)

您可以尝试使用简单的forEach

var data =   {"Data": {"Table": [{"Name": ["Jamie"],"School": ["A"],"grade": ["99"]},{"Name": ["Mike"],"School": ["B"],"grade": ["148"]}]}};

var items = [];
data['Data']['Table'].forEach(function(item){
  items.push({name: item.Name[0], grade: item.grade[0], school: item.School[0]});
});

console.log(JSON.stringify(items));