【问题标题】:Get array from nested json value objects从嵌套的 json 值对象中获取数组
【发布时间】:2020-05-10 06:54:42
【问题描述】:

我一直在寻找答案,但没有找到。

我有一个类似的数组:

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

我想转换成数组,比如省略父键:

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

也许,像 lodash 这样的库有一种方法可以实现这一点,但没有找到。任何帮助将不胜感激:)

【问题讨论】:

  • 您的问题中没有JSON,可能应该删除相应的标签。

标签: javascript arrays json ecmascript-6 lodash


【解决方案1】:

使用Array.flatMap()(或lodash的_.flatMap())迭代数组,并使用Object.values()(或_.values())获取每个项目的内部对象:

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

const result = data.flatMap(Object.values)

console.log(result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2013-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    相关资源
    最近更新 更多