【问题标题】:How to move an object property's name into a property value如何将对象属性的名称移动到属性值中
【发布时间】:2020-10-13 22:02:18
【问题描述】:

我有这个我想要转换的对象集合:

let A = [
    {
        institution: 19.5,
        region: "EUROPE",
        code: "Bosnia and Herzegovina",
        code3: "BIH"
    },
    {
        financial: 15.5,
        region: "EUROPE",
        code: "Bulgaria",
        code3: "BGR"
    },
    {
        institution: 15.9,
        region: "EUROPE",
        code: "Croatia",
        code3: "HRV"
    },
    {
        deflation: 40.6,
        region: "EUROPE",
        code: "Cyprus",
        code3: "CYP"
    }
]

我最后想要什么:

B = [
    {
        name: "institution",
        value: 19.5,
        region: "EUROPE",
        code: "Bosnia and Herzegovina",
        code3: "BIH"
    },
    {
        name: "financial",
        value: 15.5,
        region: "EUROPE",
        code: "Bulgaria",
        code3: "BGR"
    },
    {
        name: "institution",
        value: 15.9,
        region: "EUROPE",
        code: "Croatia",
        code3: "HRV"
    },
    {
        name: "deflation",
        value: 40.6,
        region: "EUROPE",
        code: "Cyprus",
        code3: "CYP"
    }
]

我已经让它与下面的代码一起工作,但我想知道是否有更优雅的方法来做到这一点?

A.forEach(e => {
    e["name"] = Object.keys(e)[0]
    e["value"] = Object.values(e)[0]
    delete e[Object.keys(e)[0]];
})

【问题讨论】:

    标签: javascript object properties transformation


    【解决方案1】:

    Object.keys() 返回一个数组,但您并没有这样对待它。

    如果您知道只有一个未知属性名称需要转置,并且您知道所有其他属性名称,您可以使用已知属性和...rest 解构对象并使用 Object.entries() 设置名称和值

    let A=[{institution: 19.5, region: "EUROPE", code: "Bosnia and Herzegovina", code3: "BIH"},
    {financial: 15.5, region: "EUROPE", code: "Bulgaria", code3: "BGR"},
    {institution: 15.9, region: "EUROPE", code: "Croatia", code3: "HRV"},
    {deflation: 40.6, region: "EUROPE", code: "Cyprus", code3: "CYP"}]
    
    
    let res = A.map(({region, code, code3, ...rest})=>{
       const [name, value] = Object.entries(rest)[0]
       return { name, value, region, code, code3 }   
    })
    
    console.log(res)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-02
      • 1970-01-01
      • 2010-12-20
      • 2020-11-05
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      相关资源
      最近更新 更多