为什么项目插入对象?

Why item inserted in object?

我在 ES6 中找到了一个 groupby 实现来对这个数据对象进行分组:

const pets = [
    {type:"Dog", name:"Spot"},
    {type:"Cat", name:"Tiger"},
    {type:"Dog", name:"Rover"}, 
    {type:"Cat", name:"Leo"}
];

但是,为什么“item”也插入到对象中,因为我们已经插入了一个键[item[key]],并且值...(result[item[key]] || []).

还有如何 console.log() 这样的表示法中的“项目”来知道那里有什么数据(像内部对象)

{...result,
[item[key]]: [
      ...(result[item[key]] || []),
      console.log(item),] // ?
}
const groupBy = (items, key) => items.reduce(
  (result, item) => ({
    ...result,
    [item[key]]: [
      ...(result[item[key]] || []),
      item,    // ?
    ],
  }), 
  {},
);

result[item[key]] 存储之前添加的项目。 item 是为了将当前项添加到数组中。

要记录 item,您可以使用 console.log returns 一个虚假值这一事实并使用 || (OR) 运算符:

(console.log(item) || item)

const pets = [
    {type:"Dog", name:"Spot"},
    {type:"Cat", name:"Tiger"},
    {type:"Dog", name:"Rover"}, 
    {type:"Cat", name:"Leo"}
];

const groupBy = (items, key) => items.reduce(
  (result, item) => ({
    ...result,
    [item[key]]: [
      ...(result[item[key]] || []),
      (console.log(item) || item),    // !!
    ],
  }), 
  {},
);

groupBy(pets, "type")

groupBy命令式(对于初学者来说可能更容易理解)版本:

const groupBy = (items, key) => {
  const result = {};
  for (const item of items) {
    const arr = result[item[key]];
    if (arr) {
      arr.push(item);
    } else {
      result[item[key]] = [item];
    }
  };
  return result;
};