To convert a JavaScript object to an array, we can use the Object.entries
method to get the key-value pairs from the object into an array.
Then we can use the JavaScript array’s map
method to return each entry in an array.
For instance, we can write:
const input = {
"fruit": ["mango", "orange"],
"veg": ["carrot"]
};
const output = Object.entries(input).map(([key, val]) => {
return {
type: key,
name: val
};
});
console.log(output)
We have the input
object that has several properties.
Then we call Object.entries
with input
to return an array of key-value pair arrays.
Next, we call map
with a callback that destructures the key-value pair from the parameter and return an object with the key
and val
set as values of the object.
Therefore, output
is:
[
{
"type": "fruit",
"name": [
"mango",
"orange"
]
},
{
"type": "veg",
"name": [
"carrot"
]
}
]