0

I am working on an Ionic 3 project,which uses Angular.

I have a JSON object like below called person. However, I have a Ionic toggle button which enables various sections based on whats returned from person.

person  = { name: "peter", job: "programmer", home: "somewhere"};

person_checked_values = {}

In order to update my toggles I need to pass a boolean. The keys are the same. How can I dynamically build a new object off of whats returned from person KEYs, but set the value as true so person_checked_values results like below?

person_checked_values  = { name: true, job: true, home: true};

I tried to foreach loop person and create a new object from that, but keep getting undefined and stumped. FWIW - I am using _lodash as well so if there is possibly someway to use help from that library its available.

1 Answer 1

1

You can use Object.keys to get all of the keys. You can then combine that with the .reduce function of arrays to build an object.

let person = {
  name: "peter",
  job: "programmer",
  home: "somewhere"
};

let result = Object.keys(person).reduce((obj, key) => {
  obj[key] = true;
  return obj;
}, {})

console.log(result);

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

1 Comment

Thanks, much appreciated. Works perfectly.

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.