我有这种形式的对象
[
{
array1: 'value1',
array2: 'value1'
},
{
array1: 'value2',
array2: 'value2'
},
{
array1: 'value3',
array2: 'value3'
}
]
我需要创建两个新的表单数组
array1['value1','value2','value3',]
array2['value1','value2','value3',]
答案 0 :(得分:0)
您可以使用下面的代码来实现
let arr = [{
array1: 'value1',
array2: 'value1'
},
{
array1: 'value2',
array2: 'value2'
},
{
array1: 'value3',
array2: 'value3'
}
],
array1 = [],
array2 = [];
arr.forEach(e => {
array1.push(e.array1);
array2.push(e.array2);
});
console.log(array1, array2)
答案 1 :(得分:0)
使用map
:
const arr = [{array1:'value1',array2:'value1'},{array1:'value2',array2:'value2'},{array1:'value3',array2:'value3'}];
const array1 = arr.map(({ array1 }) => array1);
const array1 = arr.map(({ array2 }) => array2);
console.log(array1);
console.log(array2);
或者您可以使用reduce
来提高效率:
const arr = [{array1:'value1',array2:'value1'},{array1:'value2',array2:'value2'},{array1:'value3',array2:'value3'}];
const [array1, array2] = arr.reduce(([a, b], { array1, array2 }) => (a.push(array1), b.push(array2, [a, b]), []);
console.log(array1);
console.log(array2);