我有一个对象数组,如下所示。如果该数组包含键值相同的对象,则生成的数组应包含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"
}
]
}
]
有人可以帮助我实现这一目标吗?预先感谢
答案 0 :(得分:1)
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)
下面的代码应该可以得到预期的结果。
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;
}, [])
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;
}, []);
答案 1 :(得分:0)
使用object
和array
var arr = [{
"abc": [{
"name": "test",
"addr": "123",
}]
},
{
"def": [{
"first_name": "test",
"last_name": "test"
}]
},
{
"def": [{
"first_name": "test1",
"last_name": "test1"
}]
}
]
var b = {}
arr.forEach(c => {
var key = Object.keys(c)[0]
var value = Object.values(c)[0]
if (!b[key]) b[key] = []
b[key].push(...value)
})
// b is resultant object
var c = []
Object.keys(b).forEach(v => {
let a = {};
a[v] = b[v];
c.push(a)
})
// c is converting object to array
console.log(c)