我一直在尝试使用数组的reduce方法在一个对象中汇总两个条目对象的列表,但是作为回报,我得到的是最后一个条目之一的值。代码:
const swatches = [
{ emoji: "lion" , color: "#ff691f" },
{ emoji: "tiger" , color: "#fab81e" },
{ emoji: "fish" , color: "#7fdbb6" },
{ emoji: "frog" , color: "#19cf86" },
{ emoji: "pig" , color: "#f58ea8" },
{ emoji: "unicorn" , color: "#981ceb" },
{ emoji: "rabbit" , color: "#ffffff" },
{ emoji: "wolf" , color: "#000000" },
]
const animals = swatches.reduce( (emojis, entry) => emojis[entry.emoji] = entry.color, {} )
最佳答案
您将需要从回调中返回(“新”)累加器(您的emojis
对象),以用于下一次迭代或用作最终结果:
const animals = swatches.reduce((emojis, entry) => {
emojis[entry.emoji] = entry.color;
return emojis;
}, {});
使用普通循环可能会更简单:
const animals = {};
for (const entry of swatches)
animals[entry.emoji] = entry.color;
关于javascript - 尝试使用reduce方法将单个对象中的对象折叠起来,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58894803/