我的第一个数组称为 feed:
[
{
_id: '5b8906e81248270685399a9a',
name: 'fin24',
state: 'OK',
status: true,
},
{
_id: '5b8907031248270685399a9b',
name: 'news24',
state: 'OK',
status: true,
}
]
我的第二个数组称为 feedArticlesCount:
feedArticlesCount: [
{ _id: 5b8907031248270685399a9b,
pending: 21,
approved: 1,
active: 21,
inactive: 1 },
{ _id: 5b8906e81248270685399a9a,
pending: 20,
approved: 0,
active: 20,
inactive: 0 },
{ _id: 5b8664c26d90b107d0952cbe,
pending: 62,
approved: 8,
active: 0,
inactive: 70 },
{ _id: 5b865bf28152610775987d67,
pending: 111,
approved: 30,
active: 0,
inactive: 141 }
]
我想根据匹配的 _id 值将这两个数组合并为一个,如果第一个数组中不存在 _id 我想跳过它。
我的预期输出:
[
{
_id: '5b8906e81248270685399a9a',
name: 'fin24',
state: 'OK',
status: true,
pending: 20,
approved: 0,
active: 20,
inactive: 0
},
{
_id: '5b8907031248270685399a9b',
name: 'news24',
state: 'OK',
status: true,
pending: 21,
approved: 1,
active: 21,
inactive: 1
}
]
我尝试使用 forEach 和 reduce 方法,但它无法正常工作
这里我尝试过:
let result = [];
feeds.forEach((itm, i) => {
result.push(Object.assign({}, itm, feedArticlesCount[i]));
});
console.log(result);
这是有效的,但我的名称 key 存储在错误的 _id 位置。
最佳答案
因为第二数组包含第一个数组中不存在的项目,所以您可以.map
由第一个数组代替,并且 .find
第二个数组中的匹配对象:
const arr=[{_id:'5b8906e81248270685399a9a',name:'fin24',state:'OK',status:!0,},{_id:'5b8907031248270685399a9b',name:'news24',state:'OK',status:!0,}];
const feedArticlesCount=[{_id:'5b8907031248270685399a9b',pending:21,approved:1,active:21,inactive:1},{_id:'5b8906e81248270685399a9a',pending:20,approved:0,active:20,inactive:0},{_id:'5b8664c26d90b107d0952cbe',pending:62,approved:8,active:0,inactive:70},{_id:'5b865bf28152610775987d67',pending:111,approved:30,active:0,inactive:141}]
console.log(arr.map(
({ _id, ...rest }) => ({ _id, ...rest, ...feedArticlesCount.find((item) => item._id === _id) })
));
为了降低复杂性,您可以转换 feedArticlesCount
数组到索引为 _id
的对象中第一个( O(N)
而不是嵌套的 .find
的 O(N^2)
):
const arr=[{_id:'5b8906e81248270685399a9a',name:'fin24',state:'OK',status:!0,},{_id:'5b8907031248270685399a9b',name:'news24',state:'OK',status:!0,}];
const feedArticlesCount=[{_id:'5b8907031248270685399a9b',pending:21,approved:1,active:21,inactive:1},{_id:'5b8906e81248270685399a9a',pending:20,approved:0,active:20,inactive:0},{_id:'5b8664c26d90b107d0952cbe',pending:62,approved:8,active:0,inactive:70},{_id:'5b865bf28152610775987d67',pending:111,approved:30,active:0,inactive:141}]
const articlesById = feedArticlesCount.reduce((a, { _id, ...rest }) => {
a[_id] = rest;
return a;
}, {});
console.log(arr.map(
({ _id, ...rest }) => ({ _id, ...rest, ...articlesById[_id] })
));
关于javascript - 如何根据键匹配值将两个对象数组合并为一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52112739/