Skip to content
Advertisement

How to convert multiple object to just one object with Javascript?

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"
    "class": ["art","math"]
  },
  "098": {
    "name": "yourname2"
    "class": ["art"]
  },
  "456": {
    "name": "yourname3"
    "class": ["math"]
  }
}

output i expected:

{
    "number": "123",
    "name": "yourname1"
    "class": ["art","math"]
  },
  {
    "number": "098"
    "name": "yourname2"
    "class": ["art"]
  },
  {
    "number": "456"
    "name": "yourname3"
    "class": ["math"]
  }
}

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

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement