简体   繁体   中英

Create new object from existing object with new values Angular / Ionic 3

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM