You're on the right track with Object.values, but I'd use Object.entries since it gives you both the property name and its value. Then it's a map:
const result = Object.entries(employees).map(([name, value]) => ({...value, _id: name}));
Live Example:
const employees = {
"0813562121": {
"city": "Melbourne",
"name": "Allison"
},
"8753452122": {
"city": "Melbourne",
"name": "Aria"
}
};
const result = Object.entries(employees).map(([name, value]) => ({...value, _id: name}));
console.log(result);
That uses:
Object.entries to get an array of [name, value] pairs from the object.
map to map the entries of that array into a different format
- A concise-form arrow function for the
map callback (more in a moment).
- Destructuring in the
map callback's parameter list to get the name and value in named parameters.
- Spread syntax inside an object literal to spread out the own, enumerable properties of the objects into a new object, adding the
_id property
Alternatively, you could modify the object rather than creating a new one, so that non-enumerable, or non-own properties are retained:
const result = Object.entries(employees).map(([name, value]) => {
value._id = name;
return value;
});
Live Example:
const employees = {
"0813562121": {
"city": "Melbourne",
"name": "Allison"
},
"8753452122": {
"city": "Melbourne",
"name": "Aria"
}
};
const result = Object.entries(employees).map(([name, value]) => {
value._id = name;
return value;
});
console.log(result);
The key thing there is that the same objects are in both employees and result, whereas with the first one we make a shallow copy.