How to convert object into array of objects

7.8k Views Asked by At

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.

3

There are 3 best solutions below

0
Ketan Yekale On BEST ANSWER

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);

0
Георги Лалев On
"mongo": {
  "status": true,
  "err": ""
}

is not really an object or valid syntax in that matter. You can have

[
  {
    "status": true,
    "err": ""
  },
  {
    "status": true,
    "err": ""
  },
  {
    "status": true,
    "err": ""
  }
]

from this

Object.keys(obj).reduce((arr, key)=>arr.concat(obj[key]), []);

assuming obj is your object and your free to use ES6 syntax. Or you can have this:

[
  {
    "mongo": {
      "status": true,
      "err": ""
    }
  },
  {
    "redis": {
      "status": true,
      "err": ""
    }
  },
  {
    "rabbitmq": {
      "status": true,
      "err": ""
    }
  }
]

from this:

Object.keys(obj).reduce((arr, key)=>{
    const subObj = {[key]: obj[key]};
    return arr.concat(subObj)
}, []);
0
AudioBubble On

incorrect expected output, as you mentionned, it's not an array it can be as follow :

[
        {
            "name": "mongo",
            "status": true,
            "err": ""
        },
        {
            "name" : "redis",
            "status": true,
            "err": ""
        },
        {
            "name" : "rabbitmq",
            "status": true,
            "err": ""
        }
]

and to obtain such an output, you must write a custom function for that.