1

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.

2
  • Can the values also be objects like this? Commented May 2, 2022 at 14:19
  • Object.keys(myObj).reduce((o, k) => ({ ...o, [k]: myObj[k].value }), {}) or plain iteration. Commented May 2, 2022 at 14:22

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.