gpt4 book ai didi

javascript - 尝试自定义平面 map es2017 Javascript 时留下数组

转载 作者:行者123 更新时间:2023-12-02 22:32:29 25 4
gpt4 key购买 nike

当我尝试使用reduce和concat来实现自定义平面 map 时,我得到了一个剩余的数组。我必须使用reduce concat组合,因为平面 map 在es2017中不起作用,因为我需要使用es2017。

我的代码:

function flat(object) {
return Object
.entries(object)
.reduce((acc,[k, v]) => acc.concat([k, ...v.map((s) => `${s} ${k}`)]));
}

var data = { message: { arctic: [], atlantic: ["north", "south"], indian: [], pacific: ["north", "south"], southern: [] } },
result = { message: flat(data.message) };

console.log(result);

我的结果:

{
message:(10) [
"arctic",
[],
"atlantic",
"north atlantic",
"south atlantic",
"indian",
"pacific",
"north pacific",
"south pacific",
"southern"
]
}

我需要什么:

{
message:(9) [
"arctic",
"atlantic",
"north atlantic",
"south atlantic",
"indian",
"pacific",
"north pacific",
"south pacific",
"southern"
]
}

最佳答案

您需要将空数组的初始值传递给reduce,否则reduce中acc的第一个值将是对象的第一个条目(对象的第一个条目是 ['arctic', []]。但是您希望所有键值对都具有映射逻辑(连接键、然后连接键的数组可能具有的任何值)应用于它们,您不想排除第一项:

function flat(object) {
return Object
.entries(object)
.reduce((acc, [k, v]) => acc.concat([k, ...v.map((s) => `${s} ${k}`)]), []);
// ---------------------------> ^^
}

var data = {
message: {
arctic: [],
atlantic: ["north", "south"],
indian: [],
pacific: ["north", "south"],
southern: []
}
},
result = {
message: flat(data.message)
};

console.log(result);

关于javascript - 尝试自定义平面 map es2017 Javascript 时留下数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58848995/

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