通过键组合两个对象数组,并将第二个数组的值推入第一个数组内的新数组中

时间:2017-11-02 01:07:12

标签: javascript arrays

我需要一个结果数组,它包含两个数组的数据。如果名称相同,请将第二个数组的值添加到第一个数组的数组中。最好的方法是什么?

var array1 = [
  {name: "name1", type: "type"},
  {name: "name2", type: "type"},
  {name: "name3", type: "type"}
]

var array2 = [
  {name: "name1", value: "value1"},
  {name: "name2", value: "value2"},
  {name: "name2", value: "value3"},
  {name: "name2", value: "value4"}
]

var result = [
  {name: "name1", type: "type", values: [
    "value1"
  ]},
  {name: "name2", type: "type", values: [
    "value2",
    "value3",
    "value4"
  ]},
  {name: "name3", type: "type", values:[]}
]

4 个答案:

答案 0 :(得分:1)

以下是我的方法(请注意,它会修改array1):

var array1 = [
  {name: "name1", type: "type"},
  {name: "name2", type: "type"},
  {name: "name3", type: "type"}
]

var array2 = [
  {name: "name1", value: "value1"},
  {name: "name2", value: "value2"},
  {name: "name2", value: "value3"},
  {name: "name2", value: "value4"}
]

var result = array1.map(item => {
  item.values = array2
    .filter(x => x.name === item.name)
    .map(x => x.value)
    
  return item
})

console.log(result)

答案 1 :(得分:0)

基于ES6 Array.prototype mapreduce方法以及spread opearator的单行解决方案:

const result = array1.map(a1 => Object.assign({}, a1, { values: 
  array2.reduce((r, a2) => a2.name === a1.name ? r.push(a2.value) && r : r, [])
}));

没有传播操作符的版本但使用ES6 Object.assign

console.log(x) //x is not declared -> reference error


var x = new Object();
console.log(x.property); //console.log: undefined

答案 2 :(得分:0)

您可以使用Array.prototype.map(),Array.prototype.filter()和ES6扩展运算符来完成这项工作。



var array1 = [
  {name: "name1", type: "type"},
  {name: "name2", type: "type"},
  {name: "name3", type: "type"}
]

var array2 = [
  {name: "name1", value: "value1"},
  {name: "name2", value: "value2"},
  {name: "name2", value: "value3"},
  {name: "name2", value: "value4"}
]

let result = array1.map(item1 => ({
  ...item1,
  values: array2
    .filter(item2 => item2.name === item1.name)
    .map(item2 => item2.value)
}));

console.log(result);




答案 3 :(得分:0)

除了名为name3的空数组之外,它为您提供了所有内容,您可以通过循环遍历array1的每个元素并添加一个空数组来轻松添加它。

var array1 = [
  {name: "name1", type: "type"},
  {name: "name2", type: "type"},
  {name: "name3", type: "type"}
];

var array2 = [
  {name: "name1", value: "value1"},
  {name: "name2", value: "value2"},
  {name: "name2", value: "value3"},
  {name: "name2", value: "value4"}
];

for(let i = 0; i < array2.length; i++){
  let data = array2[i];
  for(let j = 0; j < array1.length; j++){
    if(array1[j].name == array2[i].name){
      if(array1[j].value == undefined) array1[j].value = [];
      array1[j].value.push(array2[i].value);

    }
  }
}

console.log(array1);