I have a javascript object that I would like to convert into an array of objects
{
"mongo": {
"status": true,
"err": ""
},
"redis": {
"status": true,
"err": ""
},
"rabbitmq": {
"status": true,
"err": ''
}
}
The expected output must be
[
"mongo": {
"status": true,
"err": ""
},
"redis": {
"status": true,
"err": ""
},
"rabbitmq": {
"status": true,
"err": ""
}
]
What is the correct way to achieve this with javascript code?
Thanks.
Your expected output is not syntactically correct in javascript. JS arrays can have only numeric indices starting from 0. In you expected output, you have shown string keys.
The syntactically and symantically correct output would be:
[
{
"name": "mongo",
"status": true,
"err": ""
},
{
"name": "redis",
"status": true,
"err": ""
},
{
"name": "rabbitmq",
"status": true,
"err": ""
}
]
JS Code to achieve this:
var obj = {
"mongo": {
"status": true,
"err": ""
},
"redis": {
"status": true,
"err": ""
},
"rabbitmq": {
"status": true,
"err": ''
}
};
var arr = [];
for (key in obj) {
arr.push(Object.assign(obj[key], {name: key}));
}
console.log('sdf', arr);