gpt4 book ai didi

javascript - 尝试使用reduce方法将对象数组折叠为单个对象

转载 作者:行者123 更新时间:2023-11-28 16:56:58 24 4
gpt4 key购买 nike

我一直在尝试使用数组的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, {} )

最佳答案

您需要返回累加器表情符号

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),
{}
);

console.log(animals);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 尝试使用reduce方法将对象数组折叠为单个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58894803/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com