Albert
Albert

Reputation: 49

Get array from nested json value objects

I've been searching an answer for that but didn't found it.

I have an array like:

const data2 = [{
    "abc":{
            companyCity:"Cupertino",
            conpanyName:"Apple"
        }
    },
    {
    "def":{
            companyCity:"Mountain View",
            conpanyName:"Google"
        }
    }
]  

And I'd like to convert to and array like omiting the parent keys:

const data3 = [
    {
        companyCity:"Cupertino",
        companyName:"Apple",
    },
    {
        companyCity:"Mountain View",
        companyName:"Google"
    }
]

Perhaps, libraries like lodash have a method to achieve that, but didn't find it. Any help would be very appreciated :)

Upvotes: 0

Views: 53

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

Iterate the array with Array.flatMap() (or lodash's _.flatMap()), and get the an the inner object of each item using Object.values() (or _.values()):

const data = [{"abc":{"companyCity":"Cupertino","conpanyName":"Apple"}},{"def":{"companyCity":"Mountain View","conpanyName":"Google"}}]

const result = data.flatMap(Object.values)

console.log(result)

Upvotes: 2

Related Questions