[英]Append the common object in one array and remove duplicates
我正在尝试从Javascript数组中删除重复的对象。
我有一个这样的物体
var actualObj = [
{
"name": "Sam",
"id": "1",
"dept": "Inventory",
"info": {
"key1": "test1",
"key2": "test2",
"key3": "test3"
}
},
{
"name": "Paul",
"id": "2",
"dept": "Inventory",
"info": {
"key1": "test1",
"key2": "test2",
"key3": "test3"
}
},
{
"name": "Sam",
"id": "1",
"dept": "Inventory",
"info": {
"key4": "test4",
"key5": "test5",
"key6": "test6"
}
}
]
我试图删除重复项并将“信息”组合到对象数组中,就像这样
var expectedObj = [
{
"name": "Sam",
"id": "1",
"dept": "Inventory",
"info": [
{
"key1": "test1",
"key2": "test2",
"key3": "test3"
},
{
"key4": "test4",
"key5": "test5",
"key6": "test6"
}
]
},
{
"name": "Paul",
"id": "2",
"dept": "Inventory",
"info": {
"key1": "test1",
"key2": "test2",
"key3": "test3"
}
}
]
在“ info”对象中使用相同的值,我尝试使用Lodash,它可以很好地运行JSFIDDLE
任何人都可以帮助我从实际目标中实现预期目标。 我正在尝试通过组合为具有相似id值的一个对象来创建期望的对象。
您可以尝试一下,希望它对您有用。
for(let i = 0; i < actualObj.length; i++) {
let o = actualObj[i];
for(let j = i+1; j < actualObj.length; j++) {
let b = actualObj[j];
// dublicate object identified by id
if (o.id === b.id) {
const info = [];
info.push(o.info);
info.push(b.info);
o.info = info;
actualObj.splice(j, 1);
}
}
}
如果您的重复对象是由其他属性(例如name和dept)标识的,则只需更新if条件,例如
if (o.id === b.id && o.name === b.name && o.dept === b.dept)
使用lodash, _.groupBy()
的项目由id
,然后_.map()
组到所请求的格式,使用_.omit()
来获得无信息基本对象,并_.map()
得到一个info
数组。 使用_.assign()
合并为一个对象:
var actualObj = [{"name":"Sam","id":"1","dept":"Inventory","info":{"key1":"test1","key2":"test2","key3":"test3"}},{"name":"Paul","id":"2","dept":"Inventory","info":{"key1":"test1","key2":"test2","key3":"test3"}},{"name":"Sam","id":"1","dept":"Inventory","info":{"key4":"test4","key5":"test5","key6":"test6"}}]; var result = _(actualObj) .groupBy('id') .map(function(group) { return _.assign(_.omit(group[0], 'info'), { info: _.map(group, 'info') }); }) .value(); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.