I want to make this object:
let data = {
"car": {
"model": 1999
},
"van": {
"model": 1850
}
}
to look like this:
let data = {
"car" : 1999,
"van": 1850
}
the goal is to remove the key model and keep its value.
let data = {
"car": {
"model": 1999
},
"van": {
"model": 1850
}
}
const dataFormated = Object.entries(data).reduce((acc, [k, {model}]) => ({...acc, [k] : model}), {})
You can do using this approach
let data = {
"car": {
"model": 1999
},
"van": {
"model": 1850
}
}
let result = Object.keys(data).map(function(e){
return {[e] : data[e]['model']};
});
You can grab the Object.entriesfrom the data object (key/value pairs in an array), and then iterate over them to update a new object.
const data={car:{model:1999},van:{model:1850}};
// Initialise a new object
const out = {};
// Get the entries from the data
// Each entry will be an array with
// a key/value pair:
// ["car", { "model": 1999 }]
const entries = Object.entries(data);
// Then for each of those arrays destructure
// the key and obj, and update your new object
// using that information
for (const [key, obj] of entries) {
out[key] = obj.model;
}
// Ta da!
console.log(out);
Additional documentation