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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can map the Object.entries since there is 1:1 of the entries to the array item
const obj = {
"123": { "name": "yourname1", "class": ["art","math"] },
"098": { "name": "yourname2", "class": ["class1","class2"] },
"456": { "name": "yourname3" }
};
const arr = Object.entries(obj)
.map(([key, val]) => ({ "number": key, "name": val.name, "class": val.class || [] }));
console.log(arr)
Method 2
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);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0