How can you merge objects in array of objects?

2020-02-07 00:19发布

I'm looking for the best solution to merge all objects in one array

const arrayOfObjects = [
 {name: 'Fred', surname: 'Shultz'}, {name: 'Anne', surname: 'Example'}
];

I want to achieve: {name: ['Fred', 'Anne'], surname: ['Example', 'Shultz']}

What's the best option for that (es6)? Maybe I can do something like that using lodash? Which helpers should I use?

12条回答
欢心
2楼-- · 2020-02-07 00:36

Short way with array reduce:

const arrayOfObjects = [
 {name: "name1", surname: "surname1"}, {name: 'Anne', surname: 'Example'}, {name: 'name3', surname: 'Example3'}
];
/*
{name: ['Fred', 'Anne'], surname: ['Example', 'Shultz']}
*/
var result = arrayOfObjects.reduce((obj,current)=>{
    (obj['name'] = obj['name']||[]).push(current.name);
    (obj['surname'] = obj['surname']||[]).push(current.surname);
    return obj;
},{});
console.log(result);

查看更多
Explosion°爆炸
3楼-- · 2020-02-07 00:36

Don't make it any more complicated than it needs to be:

const arrayOfObjects = [
    {name: 'Fred', surname: 'Shultz'},
    {name: 'Anne', surname: 'Example'}
];

const result = {name:[], surname:[]};
for (const obj of arrayOfObjects)
    for (const prop in result)
        result[prop].push(obj[prop]);

I will assume that you statically know the property names that your result should have - one can't really do it dynamically anyway as that wouldn't work properly for an empty input array.

查看更多
Summer. ? 凉城
4楼-- · 2020-02-07 00:41

Here is a lodash approach

  _(input).flatMap(_.entries).groupBy(0).mapValues(v => _.map(v, 1)).value()

var input = [
 {name: 'Fred', surname: 'Shultz'}, {name: 'Anne', surname: 'Example'}
];

var res =   _(input).flatMap(_.entries).groupBy(0).mapValues(v => _.map(v, 1)).value()

console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

This will take care if the objects doesn't have exactly same key sets

查看更多
姐就是有狂的资本
5楼-- · 2020-02-07 00:48

You could do it like this:

const arrayOfObjects = [
  {name: 'Fred', surname: 'Shultz'}, {name: 'Anne', surname: 'Example'}
];

const result = {};
arrayOfObjects.forEach(item => {
  Object.keys(item).forEach(key => {
    if (!result[key]) {
      result[key] = [];
    }
    result[key].push(item[key]);
  });
});

console.log(result);

查看更多
一纸荒年 Trace。
6楼-- · 2020-02-07 00:48

Without any library

const mergeObjectInArray=(input)=>{
const myObj={};
Object.keys(input[0]).forEach(key=>myObj[key]=input.map(inp=>inp[key]));
return myObj;
}
查看更多
叼着烟拽天下
7楼-- · 2020-02-07 00:53

with pure javascript

var myInput = [{ a: 1, b: 2, c: 3 }, { a: 2, b: 4, c: 6 }, { a: 7, b: 8, c: 9 }];
    var myArray = [];
    var myObject = {};
    function isArray(a){
        return Object.prototype.toString.call(a) === '[object Array]' ;
    }
    for (var i = 0; i < myInput.length; i++) {
        for (var key in myInput[i]) {
            if (myInput[i].hasOwnProperty(key)) {
                if (myArray.indexOf(key) === -1) {
                    myArray.push(key);
                    myObject[key] = myInput[i][key];
                } else {
                    if (myObject.hasOwnProperty(key)) {
                        newary = [];
                        if (isArray(myObject[key])) {
                            for (var i = 0; i < myObject[key].length; i++) {
                                newary.push(myObject[key][i]);
                            }
                        } else {
                            newary.push(myObject[key]);
                        }
                        newary.push(myInput[i][key]);
                        myObject[key] = newary;
                    }
                }
            }
        }
    }
    console.log(myObject);

查看更多
登录 后发表回答