我应该使用reduce进行映射吗?

只是想知道我应该坚持使用reduce进行映射吗?

代码很长。有没有一种方法可以使它看起来更整洁?

const items = [
 { Name: "one" },{ error: true,code: "INVALID 1" },{ Name: "two" },{ Name: "three" },code: "INVALID OTHER" },]

const filtered = items.reduce((acc,item) => {
  if (item.error === true) {
    if (!acc.errors) {
      acc.errors = [];
    }

    acc.errors.push(item);

    return acc;
  }

  if (!acc.items) {
    acc.items = [];
  }

  acc.items.push(item);

  return acc;
},{});

console.log(filtered)

yangbei1024 回答:我应该使用reduce进行映射吗?

是仅根据该对象是否包含error键确定它属于哪个对象?如果是这样,那该怎么办?

const items = [
    { Name: "one" },{ error: true,code: "INVALID 1" },{ Name: "two" },{ Name: "three" },code: "INVALID OTHER" },];

const filtered = {
    errors: items.filter(i => Object.keys(i).includes('error')),items: items.filter(i => !Object.keys(i).includes('error'))
}

console.log(filtered);

,

由于reducer的两个部分之间唯一的不同是您要按的键,因此请提取key选择,并使所有内容都取决于key

const items = [{"Name":"one"},{"error":true,"code":"INVALID 1"},{"Name":"two"},{"Name":"three"},"code":"INVALID OTHER"}]

const filtered = items.reduce((acc,item) => {
  const key = item.error ? 'errors' : 'items'
  
  if (!acc[key]) acc[key] = []

  acc[key].push(item)

  return acc
},{})

console.log(filtered)

本文链接:https://www.f2er.com/3163558.html

大家都在问