Javascript:合并两个对象数组,只有在不重复的情况下(基于指定的对象键) [英] Javascript: Merge Two Arrays of Objects, Only If Not Duplicate (Based on Specified Object Key)

查看:207
本文介绍了Javascript:合并两个对象数组,只有在不重复的情况下(基于指定的对象键)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个初始的对象数组:

Say I have an initial array of objects:

var initialData = [
    {
        'ID': 1,
        'FirstName': 'Sally'
    },
    {
        'ID': 2,
        'FirstName': 'Jim'
    },
    {
        'ID': 3,
        'FirstName': 'Bob'
    }
];

然后我获取新数据(另一个对象数组):

I then get new data (another array of objects):

var newData = [
    {
        'ID': 2,
        'FirstName': 'Jim'
    },
    {
        'ID': 4,
        'FirstName': 'Tom'
    },
    {
        'ID': 5,
        'FirstName': 'George'
    }
];

目标

我想将新数据合并为初始数据.但是,我不想覆盖初始数据数组中的任何对象.我只想添加尚不存在的对象.

Goal

I want to merge the new data into initial data. However, I don't want to overwrite any objects in the initial data array. I just want to add in objects that weren't already there.

我知道对象是根据它们的'ID'键重复的.

I know the objects are duplicates based on their 'ID' key.

我知道我可以通过遍历新数据,检查是否在初始数据中存在,如果不存在,则推送到初始数据中来做到这一点.

I know I can do this by looping through the new data, checking to see if it exists in the initial data, and if not, pushing into initial data.

for ( var i = 0, l = newData.length; i < l; i++  ) {

    if ( ! key_exists( newData[i].key, initialData ) ) {  // key_exists() is a function that uses .filter() to test.

        initialData.push( newData[i] );

    }


}

不过,我担心性能.我知道有很多新的ES6处理数组的方法,所以我希望有人有更好的主意.

I'm concerned about performance, though. I know there are lots of new ES6 ways of manipulating arrays, so I'm hoping someone has a better idea.

在忽略新数据重复项的同时,将新数据合并到初始数据中的最佳方式(最好是最佳性能)是什么?

What is the best way (best as in best performance) of merging the new data into the initial data, while ignoring duplicates in new data?

推荐答案

您可以从initialData创建一组ID,这将使检查ID是否已存在于初始数据中"更快-O(1):

You can create a set of IDs from initialData and this will make "check if ID is already in initial data" faster - O(1):

var initialData = [{
    'ID': 1,
    'FirstName': 'Sally'
  },
  {
    'ID': 2,
    'FirstName': 'Jim'
  },
  {
    'ID': 3,
    'FirstName': 'Bob'
  }
];

var newData = [{
    'ID': 2,
    'FirstName': 'Jim'
  },
  {
    'ID': 4,
    'FirstName': 'Tom'
  },
  {
    'ID': 5,
    'FirstName': 'George'
  }
];

var ids = new Set(initialData.map(d => d.ID));
var merged = [...initialData, ...newData.filter(d => !ids.has(d.ID))];

console.log(merged);

此方法的最终运行时间为 O(n + m).

The final runtime of this approach is O(n + m).

如果想提高效率,可以考虑循环遍历newData并将任何新元素手动推送到最终结果数组中(而不是使用filter和散布运算符).

If you want to be slightly more efficient, you can consider looping through newData and pushing any new elements to the final result array manually (instead of using filter and the spread operator).

这篇关于Javascript:合并两个对象数组,只有在不重复的情况下(基于指定的对象键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆