Home > database >  Create objects from main key and value from nested object
Create objects from main key and value from nested object

Time:05-02

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.

CodePudding user response:

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"
// }

CodePudding user response:

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)

  • Related