如何将JSON数组转换为JSON对象?
我有一个JSON数组。 我需要把这个:
[ {"id": ["1"], "title": ["hello"], "start": ["2016-05-20"], "end": ["2016-05-25"], } ]
对此:
[ {"id": "1", "title: "hello", "start": "2016-05-20", "end": "2016-05-25", } ]
怎么做?
您可以使用Array#forEach()
循环,并为第一个元素指定所有属性。
var array = [{ "id": ["1"], "title": ["hello"], "start": ["2016-05-20"], "end": ["2016-05-25"], }]; array.forEach(function (a) { Object.keys(a).forEach(function (k) { a[k] = a[k][0]; }); }); console.log(array);
使用forEach
和Object.keys()
var data = [{ "id": ["1"], "title": ["hello"], "start": ["2016-05-20"], "end": ["2016-05-25"], }]; data.forEach(function(obj) { Object.keys(obj).forEach(function(v) { obj[v] = obj[v][0]; }); }); console.log(data);
我们可以使用.map
和for-in
循环
var test = [ {"id": ["1"], "title": ["hello"], "start": ["2016-05-20"], "end": ["2016-05-25"], } ] test.map(function(x){ for(var key in x){ x[key] = x[key].join('') } return x; });