Search code examples
javascriptobjectpropertiestransformation

How to move an object property's name into a property value


I have this collection of objects that I would like to transform:

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"
    }
]

What I would like to have in the end:

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"
    }
]

I have got it working with the code below, but I am wondering if there is a more elegant way to do this?

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

Solution

  • Object.keys() returns an array but you are not treating it as such.

    If you know there is only one unknown property name you need to transpose and you know all the other property names you could de-structure the object using the known properties and ...rest and use Object.entries() to set up the name and value

    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)