包含数组的对象 - 是否有更简单的方法来编写这种常见模式

Object containing arrays - is there a simpler way to write this common pattern

我经常想创建一个 javascript 对象并在某个索引处将项目插入到数组中。我发现自己经常写这种模式:

var obj = {}
for (let item of list) {
    if (obj[condition] == undefined) {
        obj[condition] = [item];
    } else {
        obj[condition].push(item);
    }
}

我只是觉得不断检查未定义是一件令人沮丧的事情。有更好的方法吗?

编辑:感谢 Nick 帮我找到了我喜欢的解决方案

const list = [1, 2, 3, 4, 5];
var obj = {}
for (let item in list) {
    obj[item%2] = [...obj[item%2] || [], item]
}

console.log(obj)

以及功能方法:

const list = [1, 2, 3, 4, 5];
var obj = list.reduce((acc, item) => {
    acc[item%2] = [...acc[item%2] || [], item]
    return acc;
}, {});

console.log(obj)

可以使用数组展开运算符来简化运算。 )obj[condition] = obj[condition]? [...obj[condition], item] : [item];

对于这类情况,我倾向于使用 reduce。您最终仍然需要检查数组是否存在,但您可以像下面的代码一样压缩逻辑。

const list = [{
  type: "fruit",
  item: "apple"
}, {
  type: "veggie",
  item: "corn"
}, {
  type: "fruit",
  item: "banana"
}];

const obj = list.reduce((acc, el) => {
  acc[el.type] = [...acc[el.type] || [], el.item];
  return acc;
}, {});

console.log(obj);