我有两个长度不等的对象,我想根据'mac_id'进行合并。我正在使用lodash _.merge()
,但它与变量对象长度不兼容。
obj4=[
{ mac_id: '00-17-0d-00-00-30-47-fa',
sent_mail_time: '2017-09-28 11:07:0' },
{ mac_id: '00-17-0d-00-00-30-48-18',
sent_mail_time: '2017-09-28 11:07' }
];
obj3=[
{ mac_id: '00-17-0d-00-00-30-4d-94',
notif_time: '2017-09-28 10:16:28' },
{ mac_id: '00-17-0d-00-00-30-47-fa',
notif_time: '2017-09-28 10:14:28' },
{ mac_id: '00-17-0d-00-00-30-49-58',
notif_time: '2017-09-28 10:26:28' } ]
使用_.groupBy('mac_id')
我获得了所需的数据,但没有采用结构化的方式。
我需要遵循哪些方法才能使最终结果像这样?
[
{ mac_id: '00-17-0d-00-00-30-4d-94',
notif_time: '2017-09-28 10:16:28' },
{ mac_id: '00-17-0d-00-00-30-47-fa',
sent_mail_time: '2017-09-28 11:07:0',
notif_time: '2017-09-28 10:14:28' },
{ mac_id: '00-17-0d-00-00-30-49-58',
notif_time: '2017-09-28 10:26:28' },
{ mac_id: '00-17-0d-00-00-30-48-18',
sent_mail_time: '2017-09-28 11:07' } ]
答案 0 :(得分:3)
您可以使用Object.assign():
var _ = require('lodash');
let obj4=[
{ mac_id: '00-17-0d-00-00-30-47-fa',
sent_mail_time: '2017-09-28 11:07:0' },
{ mac_id: '00-17-0d-00-00-30-48-18',
sent_mail_time: '2017-09-28 11:07' }
];
let obj3=[
{ mac_id: '00-17-0d-00-00-30-4d-94',
notif_time: '2017-09-28 10:16:28' },
{ mac_id: '00-17-0d-00-00-30-47-fa',
notif_time: '2017-09-28 10:14:28' },
{ mac_id: '00-17-0d-00-00-30-49-58',
notif_time: '2017-09-28 10:26:28' } ];
obj3.forEach(obj3Child => {
let objtToMerge;
if (!(objtToMerge = _.find(obj4,function (obj4Child) { return obj4Child.mac_id === obj3Child.mac_id; }))) {
obj4.push(obj3Child);
} else {
Object.assign(objtToMerge, obj3Child);
}
});
console.log(obj4);
答案 1 :(得分:2)
您可以通过以下方式执行此操作
obj4=[
{ mac_id: '00-17-0d-00-00-30-47-fa',
sent_mail_time: '2017-09-28 11:07:0' },
{ mac_id: '00-17-0d-00-00-30-48-18',
sent_mail_time: '2017-09-28 11:07' }
];
obj3=[
{ mac_id: '00-17-0d-00-00-30-4d-94',
notif_time: '2017-09-28 10:16:28' },
{ mac_id: '00-17-0d-00-00-30-47-fa',
notif_time: '2017-09-28 10:14:28' },
{ mac_id: '00-17-0d-00-00-30-49-58',
notif_time: '2017-09-28 10:26:28' }
];
let result= _u.groupBy(obj4.concat(obj3), 'mac_id');
result = Object.keys(result).map(e => Object.assign({}, ...result[e]));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<script>
_u = _.noConflict(); // lets call ourselves _u
</script>
答案 2 :(得分:0)
另一种方式
// merge objs
merged = obj3.concat(obj4).map( (item,index,arr) => {
let duplicates = arr.filter( v => v.mac_id == item.mac_id )
return Object.assign(...duplicates)
})
// remove duplicates
merged = [...new Set(merged)]
console.log(merged)