【问题标题】:Use a reducer with an object that have a variable key name [duplicate]对具有变量键名的对象使用 reducer [重复]
【发布时间】:2021-05-15 13:38:07
【问题描述】:

问题是:

const arr = [
  { name1: 'value1', qty: 1, time: 1 },
  { name1: 'value2', qty: 1, time: 2 },
];

// using this reducer works!
const reducer = (acc, { name1, qty}) => {
  const newQty = parseInt(acc[name1] ?? 0) + parseInt(qty); //?
  return {
    ...acc,
    [name1]: newQty
  };
};


arr.reduce(reducer, {})
// this returns: {value1: sum, value2: sum, ... }

到目前为止一切都很好......但是当你拥有这个时会发生什么?

const arr2 = [
  { name2: 'valueX', qty: 1, time: 1},
  { name2: 'valueY', qty: 1, time: 2},
];

复制粘贴然后更改名称当然可以正常工作...但是还有其他方法吗?

【问题讨论】:

标签: javascript arrays mapreduce


【解决方案1】:

这确实取决于您的具体用例,但您可以创建一个生成正确 reducer 的函数,将密钥作为输入:

const arr = [
  { name1: 'value1', qty: 1, time: 1 },
  { name1: 'value2', qty: 1, time: 2 },
];

// using this reducer works!
const makeReducer = key => (acc, cur) => {
  const newQty = parseInt(acc[key] ?? 0) + parseInt(cur.qty); 
  return {
    ...acc,
    [cur[key]]: newQty
  };
};

console.log(arr.reduce(makeReducer('name1'), {}))

const arr2 = [
  { name2: 'valueX', qty: 1, time: 1},
  { name2: 'valueY', qty: 1, time: 2},
];
console.log(arr2.reduce(makeReducer('name2'), {}))

【讨论】:

    【解决方案2】:

    原来有:

    const reducer = (acc, { time, qty, ...rest }) => {
      const name = Object.values(rest);
      const newQty = parseInt(acc[name] ?? 0) + parseInt(qty);
      return {
        ...acc,
        [name]: newQty
      };
    };
    

    只要您需要减少的所有对象都具有该格式,这将正常工作。

    (我没有测试添加不存在的键,但可能仍然可以工作......)

    您需要做的就是通过显式所有“通用”键并使用扩展运算符来捕获变化的键来“删除”。

    【讨论】:

      猜你喜欢
      • 2012-06-20
      • 1970-01-01
      • 2020-02-18
      • 2019-07-16
      • 2019-12-22
      • 2012-09-21
      • 2011-08-29
      • 1970-01-01
      • 2018-07-24
      相关资源
      最近更新 更多