Merge JavaScript Objects in Array with Same Key

Merge JavaScript objects in array with same key

Here is one option:-

var array = [{  name: "foo1",  value: "val1"}, {  name: "foo1",  value: ["val2", "val3"]}, {  name: "foo2",  value: "val4"}];
var output = [];
array.forEach(function(item) { var existing = output.filter(function(v, i) { return v.name == item.name; }); if (existing.length) { var existingIndex = output.indexOf(existing[0]); output[existingIndex].value = output[existingIndex].value.concat(item.value); } else { if (typeof item.value == 'string') item.value = [item.value]; output.push(item); }});
console.dir(output);

how to merge objects in array with same key?

I'd use a temporary object to:

  • Loop over array
  • For the current object;
    • merge ({...obj1, ...obj2}) current object to res on the ts key
  • Use Object.values to convert it to the desired array

const array = [{ts: 1596232800, v1: 1}, {ts: 1596232860, v1: 2}, {ts: 1596232920, v1: 3}, {ts: 1596232800, b2: 10}, {ts: 1596232860, b2: 11}, {ts: 1596232920, b2: 12}, {ts: 1596232800, c3: 20}, {ts: 1596232860, c3: 21}, {ts: 1596232920, c3: 22} ];

let res = {};
array.forEach(a => res[a.ts] = {...res[a.ts], ...a});
res = Object.values(res);

console.log(res);

Merge objects with same key in array of objects in javascript

var arr = [
{
"abc": [
{
"name": "test",
"addr": "123",
}
]
},
{
"def": [
{
"first_name": "test",
"last_name": "test"
}
]
},
{
"def": [
{
"first_name": "test1",
"last_name": "test1"
}
]
}]

const result = arr.reduce((acc, curr) => {
const key = Object.keys(curr)[0]
const found = acc.find(i => i[key])
if (!found) {
acc.push(curr)
} else {
found[key] = [ ...found[key], ...curr[key] ]
}
return acc;
}, [])

console.log(result)

Merge objects with the same key in 2 arrays into one array in Javascript/React

You could take a dynamic approach by using an object with wanted keys fro the final result.

const
itemsFr = [{ title: "Bonjour" }, { title: "Bonne Nuit" }],
itemsEn = [{ title: "Good Morning" }, { title: "Good Night" }],
result = Object
.entries({ fr: itemsFr, en: itemsEn })
.reduce((r, [key, a]) => a.map(({ title }, i) => ({
title: { ...r[i]?.title, [key]: title }
})), []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Combine object array if same key value in javascript

You can use reduce alongside Object.values():

var obj = [  { id: "1", prcode: "dessert" },  { id: "1", prcode: "snacks" },  { id: "2", prcode: "cafe" },  { id: "4", prcode: "all" }]
const out = obj.reduce((a, v) => { if(a[v.id]) { a[v.id].prcode = [a[v.id].prcode, v.prcode].join(',') } else { a[v.id] = v } return a}, {})console.log(Object.values(out))

Merging objects from array with the same key value

You could use reduce with Object.keys to do that.

var arr = [
{id: 1, tech_id:11, action: 'swim'},
{id: 2, tech_id:11, action: 'run'},
{id: 3, tech_id:22, action: 'climb'},
{id: 4, tech_id:22, action: 'swim'},
{id: 5, tech_id:11, action: 'jump'},
]

let mergeObj = arr.reduce((p, c) => {
const {tech_id, ...otherData} = c;

if (!(tech_id in p)) {
p[tech_id] = {
data: []
}
}

p[tech_id].data.push(otherData)
return p
}, {})

mergeObj = Object.keys(mergeObj).map(key => {
return {
tech_id: key,
data: mergeObj[key].data
}
})

console.log(mergeObj);

Merge two array of objects based on a key value compare

You can do something like this:

const users = [
{
p_id: 1,
name: "Peter",
status: "Active",
},
{
p_id: 2,
name: "Kane",
status: "Active",
},
{
p_id: 3,
name: "William",
status: "Inactive",
},
];

const phoneNumbers = [
{ p_id: 1, type: "home", no: "+01 234 5678" },
{ p_id: 1, type: "work", no: "+09 111 2223" },
{ p_id: 2, type: "home", no: "+12 345 6789" },
];

const mergeArrays = (arr1, arr2) => {
return arr1.map((obj) => {
const numbers = arr2.filter((nums) => nums["p_id"] === obj["p_id"]);
if (!numbers.length) {
obj.phone = numbers;
return obj;
}
obj.phone = numbers.map((num) => ({ type: num.type, no: num.no }));
return obj;
});
};

const result = mergeArrays(users, phoneNumbers);
console.log(result);

Combining the content of multiple objects that have the same key with that key as the property in JavaScript

You can iterate over the object keys and create a new object out of their aggregation.

You can use ES6 spread operator (...) which allows us to quickly copy all or part of an existing array or object into another array or object.

const cat1 = { med1: { a: 10, b: 12 }, med2: { c: 14, d: 16 } };
const cat2 = { med1: { e: 18, f: 20 }, med2: { g: 22, h: 24 } };
let resultObject = {};
Object.keys(cat1).map(key => { // iterate over the keys
resultObject = {
...resultObject,
[key]: {...cat1[key], ...cat2[key]} // merge two objects
}
return;
});

console.log(resultObject);


Related Topics



Leave a reply



Submit