1

I'd like to refactor a block of code which basically has to map 2 levels to the data I want. The data I want is the value of body in a object that contains ['key'] that has array of objects .

My object looks as follows,

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

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"?

3
  • why do you take an inner map without using the result? what are you doing inside the clauses? Commented Jan 6, 2021 at 15:40
  • @NinaScholz I need to access the value of body that is all. I can't access it without the inner map. Commented Jan 6, 2021 at 15:43
  • 1
    Don't use map to loop through things. Use forEach or a for loop. Use map to create a new array. Commented Jan 6, 2021 at 15:50

1 Answer 1

1

You could flat the values from the object and take a single loop.

Object 
    .values(object)
    .flat()
    .forEach(({ id, body }) => {
        // your code
    })
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.