2

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!!!

6
  • 1
    Do your original object keys really have spaces around them? Commented May 12, 2018 at 7:05
  • Original doesn't have. However, it prints key something like below " name ". Is it going to affect? Commented May 12, 2018 at 7:08
  • That's not JSON. "JSON is a textual, language-indepedent data-exchange format, much like XML, CSV or YAML." - What is the difference between JSON and Object Literal Notation? Commented May 12, 2018 at 7:12
  • Why python, java and arrays are in tags? Commented May 12, 2018 at 7:13
  • 1
    This question has nothing to do with python, java, or JSON. Commented May 12, 2018 at 7:15

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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; }

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.