I want to convert objects as shown here to array of objects:
My code:
entireObject = {
"++255 638-1527": {
"email": "info@gmail.com",
"phoneNumber": "++255 638-1527"
},
"+255 532-1587": {
"email": "uihy@gmail.com",
"phoneNumber": "+255 532-1587"
},
"+255 613-1587": {
"email": "klch@gmail.com",
"phoneNumber": "+255 613-1587",
"info": [
{
"date": "2022-02-19",
"count": 1
},
{
"date": "2022-03-17",
"count": 9
}]
}
}
I want to convert this to array of objects so, the output should look like this:
entireObject = [
{
"email": "info@gmail.com",
"phoneNumber": "++255 638-1527"
},
"email": "uihy@gmail.com",
"phoneNumber": "+255 532-1587"
},
{
"email": "klch@gmail.com",
"phoneNumber": "+255 613-1587",
"info": [
{
"date": "2022-02-19",
"count": 1
},
{
"date": "2022-03-17",
"count": 9
}]
}
}
I need the data like this in order to render it in HTML, so How can I do this?
The desired result should end with ] in order to be a valid array, not }. All you need is Object.values() as in the following demo.
const entireObject = {
"++255 638-1527": {
"email": "info@gmail.com",
"phoneNumber": "++255 638-1527"
},
"+255 532-1587": {
"email": "uihy@gmail.com",
"phoneNumber": "+255 532-1587"
},
"+255 613-1587": {
"email": "klch@gmail.com",
"phoneNumber": "+255 613-1587",
"info": [
{
"date": "2022-02-19",
"count": 1
},
{
"date": "2022-03-17",
"count": 9
}]
}
};
const arr = Object.values( entireObject );
console.log( arr );
you could do something like this:
const myObject = {
"++255 638-1527": {
email: "info@gmail.com",
phoneNumber: "++255 638-1527"
},
"+255 532-1587": {
email: "uihy@gmail.com",
phoneNumber: "+255 532-1587"
},
"+255 613-1587": {
email: "klch@gmail.com",
phoneNumber: "+255 613-1587",
info: [{
date: "2022-02-19",
count: 1
},
{
date: "2022-03-17",
count: 9
}
]
}
};
let result = Object.values(myObject).map((item) => ({ ...item
}));
console.log(result);
Just wanted to point you in the right direction as a similar question was asked and perfectly answered. Here's the link: How to convert object containing Objects into array of objects N.B. please make sure to see the answer which is voted as the best answer.