[英]How to modify all properties of an object in a functional way
I need to create a function which create a new object with all properties of in
set to true
, the function should create a new object. 我需要创建创建的所有属性的新对象的函数
in
设置为true
,则函数应该创建一个新的对象。
How to do it with vanilla js? 如何使用香草js? I can use deconstruction and latest JS.
我可以使用解构和最新的JS。
const in = {
ida:true,
idb:false,
idc:false,
ide:true
}
result wanted 想要的结果
const out = {
ida:true,
idb:true,
idc:true,
ide:true
}
You could map all keys with an new object and false
as value. 您可以将所有键映射为一个新对象,并将
false
用作值。 Later assign them to a single object. 以后将它们分配给单个对象。
const inO = { ida: true, idb: false, idc: false, ide: true }, outO = Object.assign(...Object.keys(inO).map(k => ({ [k]: true }))); console.log(outO);
Well, you could use Object.keys
and the spread operator to accomplish this: 好了,您可以使用
Object.keys
和spread操作符来完成此操作:
const input = { ida: true, idb: false, idc: false, ide: true } const out = Object.keys(input).reduce((acc, key) => ({...acc, [key]: true}), {}); console.log(out)
You can use a for..in loop which iterates over the keys of an object: 您可以使用for..in循环来迭代对象的键:
function setTrue(obj) { for (k in obj) obj[k] = true; } const o = { ida: true, idb: false, idc: false, ide: true } setTrue(o); console.log(o);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.