gpt4 book ai didi

javascript - 检查关联数组中是否存在键

转载 作者:行者123 更新时间:2023-11-29 10:32:13 24 4
gpt4 key购买 nike

告诉我,如何正确检查关联数组中键的存在?

例如:

var mydata = {
key1: '',
key2: {
subkey1: {
subkey1_1: {
value1: ''
value2" '',
},
},
subkey2: '';
},
}

if ((mydata.key2 != undefined) && (mydata.key2.subkey1 != undefined) && (mydata.key2.subkey1.subkey1_1 != undefined))
mydata.key2.subkey1.subkey1_1.value1 = 'test';

太长且令人困惑

((mydata.key2 != undefined) && (mydata.key2.subkey1 != undefined) && (mydata.key2.subkey1.subkey1_1 != undefined))

我想使用一个更简单的函数,比如

safeSet(mydata.key2.subkey1.subkey1_1.value1, 'test');

if (is_undefined(mydata.key2.subkey1.subkey1_1.value1) == true)
mydata.key2.subkey1.subkey1_1.value1 = 'test'; // now - error if 'mydata.key2.subkey1.subkey1_1' not exist

最佳答案

您可以使用 reduce() 创建自定义函数来测试嵌套属性是否存在。您可以将 key 作为字符串传递。

var mydata = {
key1: '',
key2: {
subkey1: {
subkey1_1: {
value1: '',
value2: '',
},
},
subkey2: ''
},
}

function safeSet(key, data) {
return key.split('.').reduce(function(r, e) {
return r ? r[e] : undefined;
}, data) != undefined
}

console.log(safeSet('key2.subkey1.subkey1_1.value1', mydata))

关于javascript - 检查关联数组中是否存在键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43318288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com