【问题标题】:Filter array of objects then replace过滤对象数组然后替换
【发布时间】:2019-07-18 09:45:20
【问题描述】:

我有一个要过滤的对象数组,然后返回过滤后的数组,然后与另一个数组进行比较,看看是否需要替换它。

例如,我想通过category_id = 2 过滤allItems,然后基于newItems 数组,我想返回过滤后的数组,但更新项在newItems(如果存在)。

allItems = [
  {
    'id': 1,
    'category_id': 2,
    'text': 'old',
    'child': [
      {
        'id': 2,
        'category_id': 2,
        'text': 'old'
      }
    ]
  },
  {
    'id': 3,
    'category_id': 3,
    'text': 'old'
  }
]


newItems = [
  {
    'id': 2,
    'category_id': 2,
    'text': 'new'
  }
]

所以我想返回:

results = [
  {
    'id': 2,
    'category_id': 2,
    'text': 'new'
  },
  {
    'id': 3,
    'category_id': 2,
    'text': 'old'
  },
]

现在,我有过滤部分,但我不确定如何与另一个数组进行比较并替换为更新的项目。

return this.allItems.filter( (item) => {
  return item.category_id == 2
})

【问题讨论】:

标签: javascript


【解决方案1】:

使用filter,后跟.map,将项目(如果需要)替换为新项目:

const allItems = [
  {
    'id': 1,
    'category_id': 1,
    'text': 'old'
  },
  {
    'id': 2,
    'category_id': 2,
    'text': 'old'
  },
  {
    'id': 3,
    'category_id': 2,
    'text': 'old'
  }
];
const newItems = [
  {
    'id': 2,
    'category_id': 2,
    'text': 'new'
  }
];

const newItemsById = newItems.reduce((a, item) => {
  a[item.id] = item;
  return a;
}, {});

const output = allItems
  .filter(({ category_id }) => category_id === 2)
  .map((item) => newItemsById[item.id] ? newItemsById[item.id] : item);
console.log(output);

另请注意,allItems 中的 'id': <number> 键值对需要后跟逗号,当后跟另一个键值对时,语法才有效。

【讨论】:

  • 如果我要替换的项目嵌套在另一个项目中怎么办?我修改了我的例子。
  • 只是先展平对象数组?必要时使用递归函数
猜你喜欢
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-11
  • 2014-10-23
  • 2017-10-07
  • 2021-10-02
相关资源
最近更新 更多