Home > Mobile >  object to array modification in Javascript
object to array modification in Javascript

Time:11-25

I have a object like this,

const obj = 
{
    "One": "1",
    "Two": "2",
    "Three": "3"
}

I want to convert this object in to an array, in this format,

const options = [
  { value: "1", label: "One" },
  { value: "2", label: "Two" },
  { value: "3", label: "Three" },
];

Can anybody help me how to do it in Javascript?

CodePudding user response:

you can do something like this

const obj = 
{
    "One": "1",
    "Two": "2",
    "Three": "3"
}

const transform = data => Object.entries(data)
    .map(([label, value]) => ({label, value}))
    
    
console.log(transform(obj))

CodePudding user response:

You could use a combination of Object.entries and .map

const obj =
    {
        "One": "1",
        "Two": "2",
        "Three": "3"
    }

    const options = Object.entries(obj).map(e=>{
        return {value: e[1], label: e[0]}
    })
    
    console.log(options);

CodePudding user response:

const obj = { "One": "1", "Two": "2", "Three": "3" }

const arr = Object.entries(obj).map((element)=>{
    return {value: element[1], label: element[0]}
})

console.log(arr);

CodePudding user response:

You can use .map method of array to create a new object with the shape you desire.

Ex.

Object.keys(obj).map(prop => ({label: prop, value: obj[prop]}))

CodePudding user response:

sounds like you need to use .map

You can convert your obj -> map

Example:

const yourObj = { id: 1, name: 'Fred', id: 2, name: 'Mark' };

So, USE:

const objInMap = new Map(Object.entries(yourObj));

this will be the result

console.log(objInMap); // -> {'id' => 1, 'name' => 'Fred' ; 'id' => 2, 'name' => 'Mark'}

  • Related