I'll keep it simple. Suppose I have an object like this:
let myObj = {
name:{
value: "John",
type: "contains"
},
age:{
value: "5",
type: "contains"
}
}
how can I create a new object that contains the main key but the value is just the value of its nested object, as follows:
let myNewObj = {
name: "John",
age: "5"
}
Thanks in advance.
If you just want to extract the value key for each object, you can do something like this:
let myObj = {
name:{
value: "John",
type: "contains"
},
age:{
value: "5",
type: "contains"
}
}
let newObj = {}
for (const key in myObj) {
newObj[key] = myObj[key].value;
}
console.log(newObj);
// {
// age: "5",
// name: "John"
// }
Convert the object to its entries array and map through it to return [key,value]
Then convert to a new object using Object.fromEntries
let myObj = {
name:{
value: "John",
type: "contains"
},
age:{
value: "5",
type: "contains"
}
}
let myNewObj = Object.fromEntries(Object.entries(myObj).map(([key,{value}])=>[key,value]))
console.log(myNewObj)
In general, to be able to transform all the values of an object's properties according to a mapping function, you can use Object.entries to make an array of [key, value] arrays for each property, and then use Object.fromEntries to reconstitute an object from those arrays. You can provide a generic transformation function in the middle of that operation like this:
const transformValues = (obj, transform) =>
Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, transform(value)]));
The transform function you need in your specific case will take the property value (which is an object) and just return its value property. Like this: ({ value }) => value (This is pretty easy with destructuring.)
let myObj = {
name: {
value: "John",
type: "contains"
},
age: {
value: "5",
type: "contains"
}
}
const transformValues = (obj, transform) =>
Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, transform(value)]));
const result = transformValues(myObj, ({ value }) => value);
console.log(result);