0

I have a nested array of objects like below and I'm trying to push all the values in to a single array. all the values are located in sp->it->value or sp->it->it->value

[
{
    "sp": [
            {
              "it":[
                    {"value":5}
               ]
            },
            ...
        ],
    "b": {
        ...
    }
},
{
    "sp": [
            {
              "it":[
                {"nm":5}
                ]
            }
        ],
    "b": {
        ...
    }
},
{
    "sp": [
            {
              "it":[
                {
                  "it":[
                    {"value":5}
                  ]
                }
               ]
           }
        ],
    "b": {
        ...
    }
},

]

and here is what I have tried

const getValues = (js) => {
    let values = []
    js.map((val,i) => {
        if("sp" in val) values.concat(getValues(val.sp))
        else if("it" in val) values.concat(getValues(val.it))
         else if("value" in val) values.push(val.value)
    })
    return values
}

I thought I could concatenate the returned value from the recursive call since it returns an array but the above code returns empty array. Any insights?

Edit fixed the typo on sp object. It is array of objects.

3
  • 1
    map returns an array. If you're not going to use the return value, use forEach. Commented Aug 28, 2019 at 18:13
  • @HereticMonkey it was a typo. fixed it Commented Aug 28, 2019 at 18:18
  • 1
    You didn't fix anything related to my comment. You're still using map for side effects instead of using it for its return value. Commented Aug 28, 2019 at 18:20

2 Answers 2

1

Array.prototype.concat()

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

So those lines do nothing:

if("sp" in val) values.concat(getValues(val.sp))
else if("it" in val) values.concat(getValues(val.it))

You need to write:

if("sp" in val) values = values.concat(getValues(val.sp))
else if("it" in val) values = values.concat(getValues(val.it))

And you should not use map if you don't use it's result. Use forEach instead.

Sign up to request clarification or add additional context in comments.

Comments

1

This is because you are passing val.sp to function which is not array but it is an object and .map is a property of an array

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.