【问题标题】:Why item inserted in object? [closed]为什么要在对象中插入项目? [关闭]
【发布时间】:2021-02-17 10:20:09
【问题描述】:

我在 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() "item" 来知道那里有什么数据(在对象内部)

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

【问题讨论】:

  • “但是,为什么“item”也插入到对象中……”我不太明白,但我正在努力。我在解释句之前的任何地方都没有看到“项目”作为文本。你指的是什么“项目”?
  • @Yousaf 因为您要推送一个新值并且代码大多是命令式的,所以我认为使用reduce 没有意义。 for..of 会是更好的选择。
  • @marzelin 有多种方法可以达到预期的效果。由于 OP 的问题与 reduce() 有关,我不想提出替代解决方案。

标签: javascript object ecmascript-6 reduce


【解决方案1】:

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

要记录item,您可以使用console.log 返回虚假值的事实并使用|| (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;
};

【讨论】:

    猜你喜欢
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多