简体   繁体   English

尝试自定义平面图 es2017 Javascript 时遗留的数组

[英]Left over array when trying to custom flatmap es2017 Javascript

I am getting a left over array when trying to use reduce and concat to implement a custom flatmap.尝试使用 reduce 和 concat 实现自定义平面图时,我得到了一个剩余的数组。 I have to use use the reduce concat combo as flatmap does not work in es2017 as i am required to use es2017.我必须使用 reduce concat 组合,因为 flatmap 在 es2017 中不起作用,因为我需要使用 es2017。

my code:我的代码:

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);

my results:我的结果:

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

What I need:我需要的:

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

You need to pass an initial value of an empty array to reduce , else the first value of the acc in the reduce will be the first entry of the object (and the first entry of the object is ['arctic', []] . But you want all key-value pairs to have the mapping logic (of concatenating the key, and then concatenating any values the key's array may have) applied to them, you don't want to exclude the first item:您需要将空数组的初始值传递给reduce ,否则 reduce 中acc的第一个值将是 object 的第一个条目(并且 object 的第一个条目是['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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM