gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 20:53:59 24 4
gpt4 key购买 nike

我有两个 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 对象中打印 - 。如果您能提供任何形式的帮助,我将不胜感激。

不胜感激!!!

最佳答案

首先获取所有键的列表(需要提前检查是否需要在迭代时添加-),然后使用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);

关于javascript - 如何将多个对象的值合并到一个数组对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50303737/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com