如何将多个对象的值合并到数组对象中?

时间:2018-05-12 07:05:02

标签: javascript arrays

我有两个JSON,如下所示:

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

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

我想要预期的输出:

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

但是,我尝试使用下面的代码段:

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

但是那个不会在json对象中打印-。我很感激您的任何帮助。

得到帮助!!!

3 个答案:

答案 0 :(得分:2)

首先获取所有键的列表(需要提前检查是否需要在迭代时添加-),然后使用reduce迭代每个对象并将其值添加到累加器:

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

答案 1 :(得分:0)

通过对外部对象数组使用单个循环并在运行中生成所有需要的键,这是一种稍微不同的方法。

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

答案 2 :(得分:0)

快速而肮脏的方式:

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)