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

时间:2019-11-04 21:38:38

标签: javascript node.js

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

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

const items = [
 { Name: "one" },
 { error: true, code: "INVALID 1" },
 { Name: "two" },
 { Name: "three" },
 { error: true, 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)

2 个答案:

答案 0 :(得分:3)

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

const items = [
    { Name: "one" },
    { error: true, code: "INVALID 1" },
    { Name: "two" },
    { Name: "three" },
    { error: true, 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);

答案 1 :(得分:2)

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

const items = [{"Name":"one"},{"error":true,"code":"INVALID 1"},{"Name":"two"},{"Name":"three"},{"error":true,"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)