提问者:小点点

用它的块更新数组(也是数组),保持索引不变


我所处的情况是,我需要使用现有数组的块更新该数组来执行操作。 我有一个可行的解决方案,但我在考虑性能,我需要知道我的方案是否足够好。

const parentArray = [
    {
    key: 0,
    customerId: 'customer 0',
    partyType: 'party 0',
    date: '2020-05-25T17:17:38.910Z',
  },
  {
    key: 1,
    customerId: 'customer 1',
    partyType: 'party 1',
    date: '2020-05-26T17:17:38.910Z',
  },
  {
    key: 2,
    customerId: 'customer 2',
    partyType: 'party 2',
    date: '2020-05-27T17:17:38.910Z',
  },
  {
    key: 3,
    customerId: 'customer 3',
    partyType: 'party 3',
    date: '2020-05-28T17:17:38.910Z',
  },
];

const childArray = [
    {
    key: 1,
    customerId: 'customer 01',
    partyType: 'party 01',
    date: '2020-05-25T17:17:38.910Z',
  },
  {
    key: 3,
    customerId: 'customer 21',
    partyType: 'party 21',
    date: '2020-05-27T17:17:38.910Z',
  },
];

const mergeArraysHandler = (parentArray, childArray, key) => {
    return parentArray.map((item, i) => {
      const record = childArray.find(record => record[key] === item[key]);
      if (record) {
        return record;
      }
      else {
        return item;
      }
    });
}

console.log(mergeArraysHandler(parentArray, childArray, 'key'));

正如您所看到的,我有一个方法,它包含父数组,子数组和一个唯一的道具,用来运行检查。 如预期的那样,该方法将两个数组合并在一起,保持索引不变,并更新作为父数组的现有数组。


共1个答案

匿名用户

不,它不是以良好的性能完成的,不必要的是你一次又一次地在子数组中搜索而不是通过键索引它一次。 而且很容易做到

const mergeArraysHandler = (parentArray, childArray, key) => {
  const childArrayMap = childArray.reduce((agg, v) => {
    agg[v[key]] = v
    return agg
  }) // or you can use lodash function _.keyBy instead of this

  return parentArray.map(item => childArrayMap(item[key]) || item))
}

或者使用lodash函数keyby可以在一行中完成

const mergeArraysHandler = (parentArray, childArray, key) => 
  _.values({
    ..._.keyBy(parentArray, key), 
    ..._.keyBy(childArray, key)
  })