Home > Software design >  Convery JS Object to array - keep key & value
Convery JS Object to array - keep key & value

Time:06-30

I am trying to convert an object (updatedConfig) to an array (configArray), while maintaining the same structure (and avoid further nesting).

I have tried declaring a new array const and using Object.entries to push the keys & values. I am able to get the keys but am having trouble figuring out how to achieve the nesting of array.

const configArray = [];
    
    Object.entries(updatedConfig).forEach(([key, value]) => {
        configArray.push(key);     
    })

Here is the object in question: enter image description here

CodePudding user response:

You can try something like this using Object.entries and Array.map

const configObject = {
 key1: 'value',
 key2: 1,
 key3: [1, 2, 3]

}

const configArray = Object.entries(configObject).map(([key, value]) => ({key, value}))

console.log(configArray)

  • Related