我有一个包含对象数组的数组。这是一个例子:
[ [{name: Alex, number: 2}, {name: Bill, number: 3}], [{name: John, number: 5}, {name: Aston, number: 7}]]
我想创建另一个数组,其中包含上述数组数组的所有对象,如下所示:
[{name: Alex, number: 2}, {name: Bill, number: 3}, {name: John, number: 5}, {name: Aston, number: 7}]
我写了下面的代码:
const productsInfoArray = [];
const productsRecords = customerContacts.map(i => i.products).map(product => {
product.map(i => productsInfoArray.push(i));
return productsInfoArray;
});
但是当我console.log(productsRecords)
返回一个包含所有信息的数组数组时。问题是此数组包含所需数组的12倍,因为customerContacts长度为12
答案 0 :(得分:5)
您可以按spreading将数组展平为Array.concat()
:
const data = [ [{name: 'Alex', number: 2}, {name: 'Bill', number: 3}], [{name: 'John', number: 5}, {name: 'Aston', number: 7}]]
const productsRecords = [].concat(...data)
console.log(productsRecords)
或者使用Array.reduce()
和concat用于非常大的数组,因为spread不是堆栈安全的:
const data = [ [{name: 'Alex', number: 2}, {name: 'Bill', number: 3}], [{name: 'John', number: 5}, {name: 'Aston', number: 7}]]
const productsRecords = data.reduce((r, a) => r.concat(a), [])
console.log(productsRecords)
答案 1 :(得分:1)
this problem has been resolved
var arrToConvert = [ [{name: "Alex", number: 2}, {name: "Bill", number: 3}], [{name: "John", number: 5}, {name: "Aston", number: 7}]]
var newArr = [];
for(var i = 0; i < arrToConvert.length; i++)
{
newArr = newArr.concat(arrToConvert[i]);
}
console.log(newArr);
答案 2 :(得分:1)
var data=[[{name: 'Alex', number: 2}, {name: 'Bill', number: 3}], [{name: 'John', number: 5}, {name: 'Aston', number: 7}]];
var copy = [];
for(var i=0;i<data.length;i++){
copy = copy.concat(data[i]);
}
console.log(copy);
答案 3 :(得分:1)
如果你想使用更加自我解释的代码,你可以使用传统的方式,以便将来如果你想要添加更复杂的逻辑,那么你很容易修改它。
var inputArray =[ [{name: "Alex", number: 2}, {name: "Bill", number: 3}], [{name: "John", number: 5}, {name: "Aston", number: 7}]];
var outputArray = [];
//loop over the array or arrays
inputArray.forEach((item)=>{
//loop over each array inside inputArray
item.forEach((obj) => {
//push each individual object in a new array
outputArray.push(obj);
});
});
console.log(outputArray);