简体   繁体   English

重构 Object.keys(object).map 以获取嵌套数组值。 JavaScript

[英]Refactor Object.keys(object).map to get the a nested array value. JavaScript

I'd like to refactor a block of code which basically has to map 2 levels to the data I want.我想重构一个代码块,它基本上必须 map 2 级别到我想要的数据。 The data I want is the value of body in a object that contains ['key'] that has array of objects.我想要的数据是包含对象数组的 ['key'] 的 object 中 body 的值。

My object looks as follows,我的 object 看起来如下,

const object = {
    "array-one": [
        {
            id: 1,
            body: "need_help",
      
        },
        {
            id: 2,
            body: "no_help",

        },
    ],
}

and below is how I map to get the value of body以下是我如何通过 map 获取 body 的值

const getTheBodyValue = () => Object.keys(object).map(key => {

    object[key].map((elem) => {
        const { id, body } = elem;
        if (body === 'need_help') // do something
        if (body === 'no_help')  // do something
    });
});

is there a more simpler way to achieve the value of body in "array-one" & "array-two"?有没有更简单的方法来实现“array-one”和“array-two”中 body 的值?

You could flat the values from the object and take a single loop.您可以将 object 中的值变平并采用单个循环。

Object 
    .values(object)
    .flat()
    .forEach(({ id, body }) => {
        // your code
    })

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

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