简体   繁体   English

JavaScript:连接对象数组

[英]JavaScript: Concatenate object arrays

I have two array of objects like below: 我有两个对象数组,如下所示:

array_1 = [
            {'id': 1},
            {'id': 2},
            {'id': 3},
            {'id': 4},
            {'id': 5}
          ];
array_2 = [
            {'name': 'Doe', 'age': 45},
            {'name': 'John', 'age': 35}
          ];

I want to concatenate these two arrays to make one array like this: 我想将这两个数组连接起来,使一个数组像这样:

result_array = [
                 {'id': 1, 'name': 'Doe', 'age': 45},
                 {'id': 2, 'name': 'John', 'age': 35},
                 {'id': 3},
                 {'id': 4},
                 {'id': 5}
               ]

I tried: 我试过了:

var result_array = array_1.concat(array_2);

But it gives: 但是它给出:

result_array = [
                 {'name': 'Doe', 'age': 45},
                 {'name': 'John', 'age': 35},
                 {'id': 1},
                 {'id': 2},
                 {'id': 3},
                 {'id': 4},
                 {'id': 5}
              ]

How can I do this? 我怎样才能做到这一点?

Your required output suggests that you need to merge objects in the matching position (not concatenation) from the arrays. 您所需的输出表明您需要合并数组中匹配位置(而非串联)的对象。

You can use Array.prototype.map() : 您可以使用Array.prototype.map()

The map() method creates a new array with the results of calling a provided function on every element in the calling array. map()方法创建一个新数组,并在调用数组中的每个元素上调用提供的函数。

and Object.assign() : Object.assign()

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. Object.assign()方法用于将所有可枚举的自身属性的值从一个或多个源对象复制到目标对象。 It will return the target object. 它将返回目标对象。

Try the following way: 请尝试以下方式:

 var array_1 = [ {'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5} ]; var array_2 = [ {'name': 'Doe', 'age': 45}, {'name': 'John', 'age': 35} ]; var result_array = array_1.map((obj, idx) => { if(idx < array_2.length){ obj = Object.assign(obj, array_2[idx]); } return obj; }); console.log(result_array); 

Just one more way: 只是另一种方式:

let array_1 = [
            {'id': 1},
            {'id': 2},
            {'id': 3},
            {'id': 4},
            {'id': 5}
          ]
let array_2 = [
            {'name': 'Doe', 'age': 45},
            {'name': 'John', 'age': 35}
          ]

let tmp = array_1.length > array_2.length ? array_1 : array_2

let result = tmp.reduce((acc, val, i) => {
  acc.push({...(array_1[i] || []), ...(array_2[i] || [])})
  return acc
}, [])

console.log(result)

I check for longest array in order to merge those if array_1 is smaller than array_2 . 如果array_1小于array_2我将检查最长的数组以合并它们。

Loop over array_1 and for each object in array_1, create a new object with the contents of array_1[i] and array_2[i] where i is your for loop iterator. 遍历array_1,并为array_1中的每个对象创建一个包含array_1 [i]和array_2 [i]内容的新对象,其中i是您的for循环迭代器。 Push this new object into a new array. 将此新对象推入新数组。

You can use Object.assign() to concatenate the 2 objects. 您可以使用Object.assign()串联这两个对象。

array1 = [
            {'id': 1},
            {'id': 2},
            {'id': 3},
            {'id': 4},
            {'id': 5}
          ];

array2 = [
            {'name': 'Doe', 'age': 45},
            {'name': 'John', 'age': 35}
          ];

          var newArray = [];
for (var i = 0; i < array1.length; i++) {
    var obj = array1[i];
    if (array2[i]) {
        for (key in array2[i]) {
            obj[key] = array2[i][key];
        }
        newArray.push(obj);
    }
};


          console.log(Object.assign(array1, newArray))

Concat is not what you're looking for in this case, you want to use map. 在这种情况下,您不需要使用Concat,而是要使用map。

Something like this, 像这样

array_3 = array_1.map(function(a, i){
    if(i < array_2.length){
        return Object.assign({},a, array_2[i]);
    }
    else {
        return a;
    }
});

Note: You might need additional checks to ensure condition where array_2 is longer/larger than array_1. 注意:您可能需要进行其他检查,以确保array_2比array_1长/大的条件。

Use array reduce and during each iteration check if in the array_2 have and element in that index corresponding to array_1 使用array reduce并在每次迭代期间检查array_2中的索引中array_2有和元素对应于array_1

 let array_1 = [{ 'id': 1 }, { 'id': 2 }, { 'id': 3 }, { 'id': 4 }, { 'id': 5 } ] let array_2 = [{ 'name': 'Doe', 'age': 45 }, { 'name': 'John', 'age': 35 } ] let finalArray = array_1.reduce(function(acc, curr, index) { acc.push({ id: curr.id }); if (array_2[index] !== undefined) { acc[index].name = array_2[index].name; acc[index].age = array_2[index].age } return acc; }, []); console.log(finalArray) 

You can use it as below, Object.assign - To add the two different matched object and splice - to Unset the element and append the objects at the beginning of the array. 您可以按如下方式使用它:Object.assign-添加两个不同的匹配对象和接头-取消设置元素并将对象附加在数组的开头。

 array_1 = [ {'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5} ] array_2 = [ {'name': 'Doe', 'age': 45}, {'name': 'John', 'age': 35} ] var obj; for (let key of array_1.keys()) { for (let key1 of array_2.keys()) { if(key == key1) { obj = Object.assign({}, array_1[key], array_2[key]); // Assigns matched keys array_1.splice(key, 1); // Remove the matched keys from array_1 array_1.unshift(obj); // appends the object to array_1 } } } console.log(array_1.sort()); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM