javascript - 在javascript中的对象数组中合并具有相同键的对象
问题描述
我有一个对象数组,如下所示。如果数组中有具有相同键值的对象,那么生成的数组应该包含 ES5 版本中两个对象的组合
var arr = [
{
"abc": [
{
"name": "test",
"addr": "123",
}
]
},
{
"def": [
{
"first_name": "test",
"last_name": "test"
}
]
},
{
"def": [
{
"first_name": "test1",
"last_name": "test1"
}
]
}
]
预期的输出应该是
var arr =[
{
"abc": [
{
"name": "test",
"addr": "123",
}
]
},
{
"def": [
{
"first_name": "test",
"last_name": "test"
},
{
"first_name": "test1",
"last_name": "test1"
}
]
}
]
谁能帮我解决这个问题?提前致谢
解决方案
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)
下面的代码应该给出预期的结果。
ES6
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;
}, [])
ES5
arr.reduce(function (acc, curr) {
var key = Object.keys(curr)[0];
var found = acc.find(function (i) {
return i[key];
});
if (!found) {
acc.push(curr);
} else {
found[key] = [].concat(found[key], curr[key]);
}
return acc;
}, []);
使用filter
而不是find
arr.reduce(function (acc, curr) {
var key = Object.keys(curr)[0];
var found = acc.filter(function (i) {
return i[key];
})[0];
if (!found) {
acc.push(curr);
} else {
found[key] = [].concat(found[key], curr[key]);
}
return acc;
}, []);
推荐阅读
- microsoft-dynamics - 我们应该使用哪种类型的 Xero 应用程序?
- html - 将“返回”/“上一个视图”按钮添加到将转换为 PDF 的 HTML
- node.js - 检查用户是否从 Node.js(云功能)登录 Firebase 身份验证
- sql - 根据列表值的最大 xpath 提取 xml 标签
- perl - 将 Word 文档另存为 UTF-8 编码的 HTML
- python - python文件输入如果和
- amazon-web-services - 使用 axios 时 S3 抛出 400 Bad Request
- javascript - iScroll5 问题 - 滚动时移动设备上的橡皮筋效果
- python-3.x - 为什么我使用 sys.stdout() 打印后得到 310,而不是只得到 3?
- javascript - 作为库作者,您如何为库中的 Web Worker 提供路径?