合并管理所有属性的对象数组

时间:2018-06-02 03:46:36

标签: javascript

我有2个对象数组,我想合并它们。

var fruits = [
    {name: 'pear', cultivar: '', color: 'yellowgreen', size: '6'},
    {name: 'apple', cultivar: 'Annurca', color: 'red', size: '5'},
    {name: 'apple', cultivar: 'fuji', color: 'red', size: '4'}
]; 

var quantity = [
    {name: 'pear', number: '15'},
    {name: 'apple', number: '50', scad: '2018'},
    {name: 'apple', number: '50'}
]; 

我想要的是:

var all = [
    {name: 'pear', cultivar: '', color: 'yellowgreen', size: '6', number: '15', scad: 'NaN'},
    {name: 'apple', cultivar: 'Annurca', color: 'red', size: '5', number: '50', scad: '2018'},
    {name: 'apple', cultivar: 'fuji', color: 'red', size: '4', number: '50', scad: 'NaN'}
]; 

每个元素都包含所有属性: name cultivar color size 数字 scad (如果财产不存在,则为NaN。)

1 个答案:

答案 0 :(得分:2)

只需.map阵列:



var fruits = [
    {name: 'pear', cultivar: '', color: 'yellowgreen', size: '6'},
    {name: 'apple', cultivar: 'Annurca', color: 'red', size: '5'},
    {name: 'apple', cultivar: 'fuji', color: 'red', size: '4'}
]; 

var quantity = [
    {name: 'pear', number: '15'},
    {name: 'apple', number: '50', scad: '2018'},
    {name: 'apple', number: '50'}
];

const all = fruits.map((fruit, i) => (
  { ...fruit, scad: NaN, ...quantity[i] }
));
console.log(all);