[英]Create new object from existing object with new values Angular / Ionic 3
I am working on an Ionic 3 project,which uses Angular. 我正在研究一个使用Angular的Ionic 3项目。
I have a JSON object like below called person. 我有一个像下面这样的JSON对象称为person。 However, I have a Ionic toggle button which enables various sections based on whats returned from person.
但是,我有一个Ionic切换按钮,可以根据个人返回的内容启用各个部分。
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?
如何根据人员KEY返回的内容动态构建新对象,但将值设置为true,以便person_checked_values结果如下所示?
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. 我试图foreach循环人,并从中创建一个新对象,但一直变得不确定和困惑。 FWIW - I am using _lodash as well so if there is possibly someway to use help from that library its available.
FWIW-我也正在使用_lodash,所以如果有可能可以使用该库中的可用帮助。
You can use Object.keys
to get all of the keys. 您可以使用
Object.keys
来获取所有键。 You can then combine that with the .reduce
function of arrays to build an object. 然后,您可以将其与数组的
.reduce
函数组合以构建对象。
let person = { name: "peter", job: "programmer", home: "somewhere" }; let result = Object.keys(person).reduce((obj, key) => { obj[key] = true; return obj; }, {}) console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.