我有这样的JSON数组:
var items = [
[{id:1,name:'test'},{id:2,name:'test'},...] ,
[{id:1,name:'test'},{id:2,name:'test'},...] ,
]
由此我需要一个这样的数组:
var newArray = [
{ id: 1, name: 'test' }, { id: 2, name: 'test'}, { id: 3, name: 'test'}, ...
]
现在我在for
数组上使用items
循环并存储到newArray
但是还有其他方法没有使用循环吗?
答案 0 :(得分:1)
reduce()
和concat()
演示3: ...
Spread Operator和concat()
var items = [
[{id:1,name:'test'},{id:2,name:'test'}] ,
[{id:1,name:'test'},{id:2,name:'test'}] ,
]
var flattened = [].concat.apply([], items);
console.log(flattened);

var items = [
[{id:1,name:'test'},{id:2,name:'test'}],
[{id:1,name:'test'},{id:2,name:'test'}]
];
var flattened = items.reduce(function(prev, curr) {
return prev.concat(curr);
});
console.log(flattened);

var items = [
[{id:1,name:'test'},{id:2,name:'test'}],
[{id:1,name:'test'},{id:2,name:'test'}]
];
var flattened = [].concat(...items);
console.log(flattened);

答案 1 :(得分:1)
我喜欢数组的功能和新原型,所以这里是我的demo
var items = [
[{id:1,name:'test'},{id:2,name:'test'}] ,
[{id:1,name:'test'},{id:2,name:'test'}]
]
var ll = items.reduce(function(prev, current){return prev.concat(current)})
console.log(ll)