I\'m looking for the best solution to merge all objects in one array
const arrayOfObjects = [
{name: \'Fred\', surname: \'Shultz\'}, {name: \'Anne\', surnam
easy with lodash:
grouped = _.mapValues(arrayOfObjects[0],
(val, key) => _.map(arrayOfObjects, key))
pure es6
let grouped = {};
for (let obj of arrayOfObjects)
for (let [key, val] of Object.entries(obj))
grouped[key] = (grouped[key] || []).concat(val)
if the keys differ from item to item, you could use something like this to collect them all:
grouped = _(arrayOfObjects)
.flatMap(_.entries)
.groupBy(0)
.mapValues(x => _.map(x, 1))
.value()
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.
You could reduce the array by iterating the entries and collecting the values, depending of the keys.
const
array = [{ name: 'Fred', surname: 'Shultz' }, { name: 'Anne', surname: 'Example' }],
result = array.reduce((r, o) => {
Object.entries(o).forEach(([k, v]) => (r[k] = r[k] || []).push(v));
return r;
}, Object.create(null));
console.log(result);
Without any library
const mergeObjectInArray=(input)=>{
const myObj={};
Object.keys(input[0]).forEach(key=>myObj[key]=input.map(inp=>inp[key]));
return myObj;
}
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);
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);