Home > Software engineering >  How to convert multiple object to just one object with Javascript?
How to convert multiple object to just one object with Javascript?

Time:03-09

As you can see i have a multiple object like "123", "098", and "456", i want all of those object to be inside the object of multiple object.

Example:

var obj = 
{
  "123": {
    "name": "yourname1"
  },
  "098": {
    "name": "yourname2"
  },
  "456": {
    "name": "yourname3"
  }
}

output i expected:

{
    "number": "123",
    "name": "yourname1"
  },
  {
    "number": "098"
    "name": "yourname2"
  },
  {
    "number": "456"
    "name": "yourname3"
  }
}

How can I achieve this? I'm sorry im not show any javascript code cause until now I have no idea what to do

CodePudding user response:

You can map the Object.entries since there is 1:1 of the entries to the array item

const obj = {
  "123": { "name": "yourname1" },
  "098": { "name": "yourname2" },
  "456": { "name": "yourname3" }
};

const arr = Object.entries(obj)
  .map(([key, val]) => ({ "number": key, "name": val.name }));
console.log(arr)

CodePudding user response:

var obj = {
  123: {
    name: 'yourname1',
  },
  '098': {
    name: 'yourname2',
  },
  456: {
    name: 'yourname3',
  },
};
const obj2 = Object.keys(obj).map(key => ({
  number: key,
  name: obj[key].name,
}));
console.log(obj2);

  • Related