Combine same-index objects of two arrays

前端 未结 4 1165
深忆病人
深忆病人 2021-01-25 05:19

Say I have two arrays of objects, like so:

var arr1 = [{name: \'Jay\'}, {name: \'Bob\'}];
var arr2 = [{age: 22}, {age: 30}];

I want a combined

相关标签:
4条回答
  • 2021-01-25 05:56

    You can just iterate one array and create a new array using the index from the first iteration. There are many ways to do this. Here's one:

        var arr1 = [{name: 'Jay'}, {name: 'Bob'}];
        var arr2 = [{age: 22}, {age: 30}];
    
        var combined = arr1.map(function(item, index) {
            return {name: item.name, age: arr2[index].age};
        });
        document.write(JSON.stringify(combined));

    If you really want the maximum performance, you'd have to test a number of schemes in a number of different browsers. For example, sometimes a for loop is faster than the built-in array methods in some browsers.

    var arr1 = [{name: 'Jay'}, {name: 'Bob'}];
    var arr2 = [{age: 22}, {age: 30}];
    var combined = [];
    
    for (var i = 0; i < arr1.length; i++) {
      combined[i] = {name: arr1[i].name, age: arr2[i].age};
    }
    
    document.write(JSON.stringify(combined));

    FYI, the for loop option (the second option) looks quite a bit faster in all three browsers here in a jsperf.

    0 讨论(0)
  • 2021-01-25 06:03

    the most trivial solution is (in compare to any util lib like underscore.js or similar). pros of it is it works without any dependency.

    var result = [];
    for(var i = 0; i < arr1.length; i+= 1) {
      item = {};
      item.name = arr1[i].name;
      item.age = arr2[i].age;
      result.push(item);
    }
    
    0 讨论(0)
  • 2021-01-25 06:08

    A more loosely coupled solution would be by using merge functionality of lodash library.

    This will be independent of the number of keys and key names you have in object. So in future if you decide to add keys to your object, you won't need to update the code to merge your objects.

    var _ = require('lodash');
    
    var arr1 = [{name: 'Jay'}, {name: 'Bob'}];
    var arr2 = [{age: 22}, {age: 30}];
    var arr3 = [];
    
    for (var i=0; i<arr1.length; i++) {
        arr3.push(_.merge(arr1[i], arr2[i]));
    }
    
    console.log(arr3);
    
    0 讨论(0)
  • 2021-01-25 06:13

    In a for loop:

    var arr1 = [{name: 'Jay'}, {name: 'Bob'}];
    var arr2 = [{age: 22}, {age: 30}];
    
    
    for(var i in arr1)
    {
      arr1[i]['age'] = arr2[i]['age'];
    }
    
    console.log(arr1) //[Object { name="Jay",  age=22}, Object { name="Bob",  age=30}]

    Now you have the merged result in arr1.

    0 讨论(0)
提交回复
热议问题