简体   繁体   English

将除 javascript object 中的一个值外的每个元素值设置为 false

[英]set every element value to false except one value in javascript object

I have an object like this:我有一个这样的 object:

layers = {a: false, b: false, c: false, d: false, e: false};
setLayer = (val) => {
   // set val to true and every other to false
}

I will call setLayer function on onClick event.我将在 onClick 事件上调用 setLayer function。 Like this:像这样:

<a onClick={this.setLayer('c')}>hello</a>
// this will set layers like this: {a: false, b: false, c: true, d: 
false, e: false}
<a onClick={this.setLayer('b')}>hello world</a>
// this will set layers like this: {a: false, b: true, c: false, d: 
false, e: false}

I do not want to use for loop and check for each key in obj.我不想使用 for 循环并检查 obj 中的每个键。 Beacuse obj is adding more and more object in my code.因为 obj 在我的代码中添加了越来越多的 object。

Take a variable 取一个变量

var lastUpdatedKey;

setLayer = (val) => {
    lastUpdatedKey && (layers[lastUpdatedKey] = false);
    layers[val] = true;
    lastUpdatedKey = val;
}

If you do not want to use a loop, you'll have to use a different implementation. 如果不想使用循环,则必须使用其他实现。

A very elegant solution is to use a Proxy in place of your layers object: 一个非常优雅的解决方案是使用Proxy代替您的layers对象:

 const layers = new Proxy({}, { get: function(obj, prop) { return prop === obj.__active__; }, set: function(obj, prop, value) { if (!Object.getOwnPropertyDescriptor(obj, '__active__')) { Object.defineProperty(obj, '__active__', { value: null, writable: true, configurable: false, enumerable: false, }); } obj[prop] = false; if (value === true) { obj.__active__ = prop; } } }); layers.a = true; layers.b = false; layers.c = false; console.log(layers); layers.b = true; console.log(layers); layers.c = true; console.log(layers); 

i would suggest something likethis: 我建议这样的事情:

const initrnalValues = {a: false, b: false, c: false, d: false, e: false}
const layers = {a: false, b: false, c: false, d: false, e: false};

const setLayer = var => {
 Object.assign(layers, initrnalValues, {
    [val]: true
}
}

that's it, no loops of any kind 就是这样,没有任何循环

Use Object.keys to iterate over the keys in the layers object. 使用Object.keys遍历图层对象中的键。 If the key is matching with 'val', set it to true 如果密钥与“ val”匹配,请将其设置为true

layers = {a: false, b: false, c: false, d: false, e: false};
setLayer = (val) => {
 Object.keys(layers).forEach(item => {
   item == val ? layers[item] = true: ''
 })
}
Object.keys(object).forEach(key => object[key] = false)
object[oneKeyNeedToBeTrue] = true;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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