如何根据键匹配值将两个对象数组组合为一个数组

时间:2018-08-31 09:46:33

标签: javascript arrays json object

我的第一个数组称为feeds

[
   {
      _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);

这可以正常工作,但是我的姓名密钥存储在错误的_id位置。

1 个答案:

答案 0 :(得分:2)

因为是 second 数组,其中包含第一个数组中不存在的项目,所以您可以.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的{​​{1}} ):

O(N^2)