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

查看:19
本文介绍了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天全站免登陆