如何解决在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","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,[])
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],[]);
,
使用object
和array
var arr = [{
"abc": [{
"name": "test",}]
},{
"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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。