javascript - JavaScript - 有没有办法通过指定的键属性合并 2 个对象?
问题描述
JavaScript - 有没有办法通过指定的键属性合并 2 个对象?在这种情况下,关键属性是authorId
.
注意:作者 3 和作者 1 没有匹配项,因此不应合并。
var b = [{"book": "book1", "authorId": 3},{"book": "book2", "authorId":2}];
var a = [{"authorId": 1, "author": "author1"},{"authorId": 2, "author": "author2"}];
var c = a.merge(b);
console.log(c);
期待:
[{"book": "book2", "authorId": 2, "author": "author2"}]
我试图在这里完成 SQL JOIN 的作用。
解决方案
map
通过Object.assign
从另一个数组中具有相同索引的项目:
var b = [{"book": "book1", "authorId": 1},{"book": "book2", "authorId":2}];
var a = [{"authorId": 1, "author": "author1"},{"authorId": 2, "author": "author2"}];
var c = a.map((aItem, i) => Object.assign({}, aItem, b[i]));
console.log(c);
如果您不能指望每个数组都被排序,那么您可能会reduce
进入一个由 索引的对象authorId
,然后获取该对象的值(这具有O(N)
复杂性,而不是.find
每次迭代都具有O(N^2)
复杂性):
var a = [{"authorId": 1, "author": "author1"},{"authorId": 2, "author": "author2"}];
var b = [{"book": "book1", "authorId": 1},{"book": "book2", "authorId":2}];
const reduceByAuthor = (arr, initial = {}) => arr.reduce((a, item) => {
a[item.authorId] = Object.assign((a[item.authorId] || {}), item);
return a;
}, initial);
const indexedByAuthor = reduceByAuthor(a);
reduceByAuthor(b, indexedByAuthor);
console.log(Object.values(indexedByAuthor));
如果您也不能指望每个项目在另一个数组中具有匹配项,那么reduce
两次,reduce
只有在第一个索引对象中找到匹配项时才将第二个分配给累加器(比filtering
之后更快):
var b = [{"book": "book1", "authorId": 3},{"book": "book2", "authorId":2}];
var a = [{"authorId": 1, "author": "author1"},{"authorId": 2, "author": "author2"}];
const aIndexed = a.reduce((a, item) => {
a[item.authorId] = item;
return a;
}, {});
const c = Object.values(b.reduce((a, bItem) => {
const { authorId } = bItem;
const aItem = aIndexed[authorId];
if (aItem) a[authorId] = Object.assign({}, aItem, bItem);
return a;
}, {}))
console.log(c);
推荐阅读
- php - 级联更新列关系 Laravel 5.6
- java - Java DatagramSocket 不接收数据
- perl - “使用 Mojo::Base 'Mojolicious::Plugin'” 引用语句的含义是什么?
- .net-core - 自动生成类/文件/等,例如使用 T4 文件
- java - 如何调用位于另一个实例内部的实例的 getter 方法
- java - Java - 如何检查数组的值是否包含指定的值作为属性
- javascript - 尝试使用带有奇怪错误的 signInWithCustomToken 进行身份验证
- python - Python3 - 重定向的标准错误没有正确重置?
- oracle - 如何在单引号 sql 查询中使用管道?
- sass - @for 循环中的 SASS 宽度百分比