繁体   English   中英

Javascript - 检查密钥是否存在 - 如果不存在,全部在一行中

[英]Javascript - check if key exists - if not create it, all in one line

我正在寻找一种检查密钥是否存在以及是否不创建密钥的单行方法。

var myObject = {};

//Anyway to do the following in a simpler fashion?

if (!('myKey' in myObject))
{
    myObject['myKey'] = {};
}

短路评估:

!('myKey' in myObject) && (myObject.myKey = {})
myObject['myKey'] = myObject['myKey'] || {};

评论:我通常更喜欢@Nindaff@MoustafaS提供的答案,具体取决于具体情况。

为了完整Object.assign ,您可以创建键/值,对任何不存在的键使用Object.assign 当您有要使用的默认选项/设置但允许用户通过参数覆盖时,这最有用。 它看起来像这样:

var myObject = {};
myObject = Object.assign( { 'myKey':{} }, myObject );

这是同样的事情,但输出更多:

 var obj = {}; console.log( 'initialized:', obj); obj = Object.assign( {'foo':'one'}, obj ); console.log( 'foo did not exist:', obj ); obj = Object.assign( {'foo':'two'}, obj ); console.log( 'foo already exists:', obj ); delete obj.foo; obj = Object.assign( {'foo':'two'}, obj ); console.log( 'foo did not exist:', obj );

注意: Object.assign在 IE 中不可用,但有一个 Polyfill

您可以使用 hasOwnProperty 或 typeof 来检查退出或取消定义...

如果你想获得某个键的值如果不存在,返回默认值它插入该键的新的缺省值,那么在这里你在一行中去:

> x = {}
{}
> x['k']
undefined
> x['k'] || (x['k'] = 23) // Insert default value for non-existent key
23
> x['k']
23
> x['z'] = 5
5
> x['z'] || (x['z'] = 42) // Will not insert default value because key exists
5

显然,您需要为可以映射到0nullundefined键添加一些额外的工作

有一个指定的Proxy内部类型适合此任务:

const myObj = new Proxy({}, {
  get (target, key) {
    return target.hasOwnProperty(key) && target[key] || (target[key] = {});
  }
});

typeof myObj.foo === 'object' && (myObj.bar.quux = 'norf') && myObj.bar.quux === 'norf';

您可以使用Object.keys() , Object.hasOwnProperty()

 var key = {myKey:{}}, prop = Object.keys(key).pop(), myObject = {}; if (!myObject.hasOwnProperty(prop)) {myObject[prop] = key[prop]} console.log(myObject)

JavaScript ES9 (ECMAScript 2018) 引入了扩展运算符:

myObject={myKey: {}, ...myObject}

如果myKey不存在,则将创建它,但如果存在则不会被覆盖。 例如:

let obj = {a:1,b:2}

let test1 = {...obj,a:3} // == {a:3,b:2}
let test1 = {a:1,b:2,a:3} // == {a:3,b:2}

let test2 = {a:3,...obj} // == {a:1,b:2}
let test2 = {a:3,a:1,b:2} // == {a:1,b:2}

您可以使用逻辑空赋值 (??=)

var test = {};
(test.hello ??= {}).world ??= "Hello doesn't exist!";

如果你不知道 object 的密钥是否存在你可以做类似的事情

object.key = (object.key || default value) operation

例子

const user = {};

user.stat = (user.stat || 0) + 1; // 1

如果你多次调用这个表达式,你会得到预期的行为

例子

const user = {};

user.stat = (user.stat || 0) + 1; // 1
user.stat = (user.stat || 0) + 1; // 2
user.stat = (user.stat || 0) + 1; // 3

使用像这样的三元运算符实际上是一样的

user.stat = user.stat ? user.stat + 1 : 0;

但更紧凑

暂无
暂无

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

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