user9777762
user9777762

Reputation:

How to merge values from multiple objects into an object of arrays?

I have a two JSON something like below:

var obj1 = {
    " name ":"rencho",
    " age ":23,
    " occupation ":"SE"
}

var obj2 = {
    " name ":"manu",
    " age ":23,
    " country ":"india"
}

I want the expected output:

var result = {
    "name":["rencho", "manu"],
    "age":[23, 23],
    "country":["-", "india"],
    "occupation": ["SE", "-"],
}

However, I tried using below the code snippet:

let arrGlobal = []

arrGlobal.push(obj1);
arrGlobal.push(obj2);

let mergedResult = arrGlobal.reduce(function(r, e) {
            return Object.keys(e).forEach(function(k) {
            if(!r[k]) r[k] = [].concat(e[k])
            else r[k] = r[k].concat(e[k])
            }), r
        }, {})

console.log(mergedResult);

But that one doesn't print - in json object. I would appreciate any kind of help from your side.

HELP WOULD BE APPRECIATED!!!

Upvotes: 2

Views: 111

Answers (3)

Egor
Egor

Reputation: 794

quick and dirty way:

function merge(a,b) {
  var c = b
  for (key in a){
    c[key] = [c[key], a[key]]
  }
  console.log(c) //prints merged object
}

merge(obj1, obj2)

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386578

A slightly different approach by using a single loop for the outer array of objects and which generates all needed keys on the fly.

var obj1 = { name: "rencho", age: 23, occupation: "SE" },
    obj2 = { name: "manu", age: 23, country: "india" },
    hash = new Set,
    result = {};

[obj1, obj2].forEach((o, length) => {
    Object.keys(o).forEach(k => hash.add(k));
    hash.forEach(k => {
        result[k] = result[k] || Array.from({ length }).fill('-');
        result[k].push(k in o ? o[k] : '-');
    });
});

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

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370729

First get a list of all keys (needed in advance to check whether you need to add - while iterating), then use reduce to iterate over each object and add its values to the accumulator:

var obj1 = {
    " name ":"rencho",
    " age ":23,
    " occupation ":"SE"
}

var obj2 = {
    " name ":"manu",
    " age ":23,
    " country ":"india"
}
const arr = [obj1, obj2];
const allKeys = arr.reduce((keys, obj) => {
  Object.keys(obj).forEach(key => keys.add(key))
  return keys;
}, new Set());
const merged = arr.reduce((merged, obj) => {
  allKeys.forEach((key) => {
    if (!merged[key]) merged[key] = [];
    merged[key].push(obj[key] || '-');
  });
  return merged;
}, {});
console.log(merged);

Upvotes: 2

Related Questions