根据相似性合并JavaScript中两个对象的有效方法?

发布于 2025-02-09 01:19:37 字数 423 浏览 2 评论 0原文

因此,我有两个对象:

var arr1 = [{id:1, name:John }{id:2, name:Adam }]

var arr2 = [{id:1, address:NY, number: 200}, {id:2, address:LA, number: 300}]

预期的结果是:

var newArr = [{id:1, name:John, address:NY, number: 200 }, { id:2, name:Adam, address:LA, number: 300}]

这只是数千个数据中的两个示例,我尝试绘制两个阵列并手动插入它们,但是这总是会导致超时在后端服务器上重。是否有一种有效的方法可以在诸如Lodash之类的包装中进行此类操作或轻量级解决方案来实现这一目标?

So I have two array of objects:

var arr1 = [{id:1, name:John }{id:2, name:Adam }]

var arr2 = [{id:1, address:NY, number: 200}, {id:2, address:LA, number: 300}]

and the expected result is:

var newArr = [{id:1, name:John, address:NY, number: 200 }, { id:2, name:Adam, address:LA, number: 300}]

This is just two examples out of thousands of data, I have tried mapping through two arrays and inserting them manually however this would always result in a timeout since I think looping is quite heavy on the backend server. Is there an efficient way to do such an operation or a lightweight solution in packages like lodash to achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

↘人皮目录ツ 2025-02-16 01:19:37

除非您使用的是本机模块,否则Lodash和其他软件包也将在内部循环。

假设您正在使用id将元素分组在一起,那么这可能就是您想要的

function mergeArrays(array1, array2) {
  const groups = {};

  for (const array of [array1, array2]) {
    for (const elem of array) {
      if (!groups[elem.id]) {
        groups[elem.id] = {};
      }

      Object.assign(groups[elem.id], elem);
    }
  }

  return Object.values(groups);
}

var arr1 = [{id:1, name:'John' }, {id:2, name:'Adam' }];
var arr2 = [{id:1, address:'NY', number: 200}, {id:2, address:'LA', number: 300}]

console.log(mergeArrays(arr1, arr2));

Unless you're using native module, lodash and other packages will also loop over the values internally.

Assuming that you're using id to group the elements together, this is probably what you want

function mergeArrays(array1, array2) {
  const groups = {};

  for (const array of [array1, array2]) {
    for (const elem of array) {
      if (!groups[elem.id]) {
        groups[elem.id] = {};
      }

      Object.assign(groups[elem.id], elem);
    }
  }

  return Object.values(groups);
}

var arr1 = [{id:1, name:'John' }, {id:2, name:'Adam' }];
var arr2 = [{id:1, address:'NY', number: 200}, {id:2, address:'LA', number: 300}]

console.log(mergeArrays(arr1, arr2));
山川志 2025-02-16 01:19:37

如果您可以使用Core JavaScript实现Librarie,为什么要使用Librarie

var a1 = [{id:1, name:'John' },{id:2, name:'Adam' }, {id: 3, name: 'mohit'}]

var a2 = [{id:1, address:'NY', number: 200}, {id:2, address:'LA', number: 300}, {id: 4, name:'dj', value: 'pj'}, {id: 5}]

let a3 = [...a1, ...a2].reduce((acc, x) => {
    acc[x.id] = Object.assign(acc[x.id] || {}, x);
    return acc;
}, {});
console.log('your need', Object.values(a3))

why use Librarie if you can achieve with core javascript

var a1 = [{id:1, name:'John' },{id:2, name:'Adam' }, {id: 3, name: 'mohit'}]

var a2 = [{id:1, address:'NY', number: 200}, {id:2, address:'LA', number: 300}, {id: 4, name:'dj', value: 'pj'}, {id: 5}]

let a3 = [...a1, ...a2].reduce((acc, x) => {
    acc[x.id] = Object.assign(acc[x.id] || {}, x);
    return acc;
}, {});
console.log('your need', Object.values(a3))

沫离伤花 2025-02-16 01:19:37

目前尚不清楚如何通过两个数组中的共享索引或共享id值组合元素。无论哪种方式,您都可以轻松编写使这一琐碎的简单实用程序功能。

如果是共享索引

的问题,请首先使用共享索引,我们可以做这样的事情:

const zipWith = (fn) => (xs, ys) => xs .map ((x, i) => fn (x, ys [i]))

const combine = zipWith ((x, y) => ({...x, ...y}))

const arr1 = [{id:1, name: 'John'}, {id:2, name: 'Adam'}], arr2 = [{id:1, address: 'NY', number: 200}, {id:2, address: 'LA', number: 300}]

console .log (combine (arr1, arr2))
.as-console-wrapper {max-height: 100% !important; top: 0}

我们编写了一个通用的助手函数zipwith - 您还将在许多实用程序库中找到它,该函数接受组合函数并返回一个函数,该函数获取两个列表,并返回了针对该函数的结果每个索引的两个元素。 (如果数组的长度不相同,可能会有奇怪的行为。)

然后,我们只需传递一个函数,即可自然合并两个对象,那么我们编写combine at zipwith 。我们可以将其传递对象.ASSIGN,但这将修改收到的第一个元素,这不是我喜欢的样式。

如果我们想使用共享ids,则由ID分组

,我们会以不同的方式进行操作。而不是扫描第二个列表中的元素,其中一个ID与第一个列表中的ID匹配,而使用o(m * n)的算法时间,其中<​​code> m 和n是两个数组的长度,我们可以用id作为键和包含数组中所有元素的数组的值折叠成一个对象。 > id 。这是大多数公用事业库调用groupby,将其更改为o(m + n)。我们可以在其中编写Mergeby函数,它将首先使用提供的函数进行groupby,然后合并<<的每个值中的所有元素代码> groupby 结果成单个元素。看起来像这样:

const groupBy = (fn) => (xs) => 
  xs .reduce ((a, x, _, __, k = fn (x)) => ((a [k] = a [k] || []), (a[k] .push (x)), a), {})

const mergeBy = (fn) => (...xss) => 
  Object .values (groupBy (fn) (xss .flat ())) .map (xs => Object .assign ({}, ...xs))

const combine = mergeBy (x => x .id)

const arr1 = [{id:1, name: 'John'}, {id:2, name: 'Adam'}], arr2 = [{id:1, address: 'NY', number: 200}, {id:2, address: 'LA', number: 300}]

console .log (combine (arr1, arr2))
.as-console-wrapper {max-height: 100% !important; top: 0}

这里合并groupby的第二个实用程序函数。 组合只需将其传递给ID-萃取功能即可。这次,我们很容易使用object .ASSIGN,因为我们用元素调用它,所以我们只能先对其进行一个空的对象。 1

那里在此版本中是额外的灵活性。它会使用相同的id自动处理多个值。它使您可以任意通过许多数组。因此,您可以将其与具有重复ID s或许多数组的单个数组一起使用。

课程

重要的一点是,当您便利一组有用的实用程序功能时,这两个版本都很容易编写。 groupbyzipwith可以立即使用,我很可能会添加Mergeby,这似乎也有用。这些库要么是您自己的库,要么是经过战斗测试的公共图书馆,是在您的编码工具箱中拥有的绝佳工具。


1。同样,在此输出的制造中没有突变对象。

It's not clear how you want to combine elements, by shared index in the two arrays or by shared id values. Either way, you can easily write simple utility functions that make this trivial.

With Shared Indices

First if it's a matter of shared indices, we could do something like this:

const zipWith = (fn) => (xs, ys) => xs .map ((x, i) => fn (x, ys [i]))

const combine = zipWith ((x, y) => ({...x, ...y}))

const arr1 = [{id:1, name: 'John'}, {id:2, name: 'Adam'}], arr2 = [{id:1, address: 'NY', number: 200}, {id:2, address: 'LA', number: 300}]

console .log (combine (arr1, arr2))
.as-console-wrapper {max-height: 100% !important; top: 0}

We write a generic helper function zipWith -- which you will also find in many utility libraries -- that accepts a combining function and returns a function that takes two lists and returns the result of running that function against the two elements at each index. (If the arrays are not the same length, there might be odd behavior.)

Then we write combine atop zipWith, by just passing it a function that naively merges the two objects. We could pass it Object .assign, but that will modify the first element it received, and that's not a style I enjoy.

Grouped by id

If we want to work with shared ids, we would do this a bit differently. Rather than scanning for the element in the second list with an id matching our current one from the first list, with algorithmic time of O (m * n), where m and n are the lengths of the two arrays, we can fold into an object with the id as a key and values of arrays containing all the elements from our arrays with that id. That is something most utility libraries call groupBy, and will change it to O (m + n). We can write a mergeBy function on top of that, which will first do the groupBy with a function supplied, and then merge all the elements in each of the values of the groupBy result into single elements. It looks like this:

const groupBy = (fn) => (xs) => 
  xs .reduce ((a, x, _, __, k = fn (x)) => ((a [k] = a [k] || []), (a[k] .push (x)), a), {})

const mergeBy = (fn) => (...xss) => 
  Object .values (groupBy (fn) (xss .flat ())) .map (xs => Object .assign ({}, ...xs))

const combine = mergeBy (x => x .id)

const arr1 = [{id:1, name: 'John'}, {id:2, name: 'Adam'}], arr2 = [{id:1, address: 'NY', number: 200}, {id:2, address: 'LA', number: 300}]

console .log (combine (arr1, arr2))
.as-console-wrapper {max-height: 100% !important; top: 0}

Here mergeBy is a second utility function layered atop groupBy. combine just passes it an id-extraction function. This time we're easily able to use Object .assign, since we're calling it with our elements, we can just prepend an empty object to them first.1

There is additional flexibility in this version. It automatically handles multiple values with the same id. And it allows you to pass arbitrarily many arrays. So you can use it with a single array that has duplicate ids or with many arrays.

Lesson

The important point here is that either version of this is simple to write, when you keep handy a collection of useful utility functions. groupBy and zipWith are available to me immediately, and I might well add mergeBy, which also seems useful. A library of these either your own, or a more battle-tested public library, is a great tool to have in your coding toolbox.


1. Again, no Objects were mutated in the making of this output.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文