Get array from nested json value objects

半城伤御伤魂 提交于 2021-02-11 12:15:15

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/59888093/get-array-from-nested-json-value-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!