{
"testPositionSeq": "12345",
"test": {
"testSeq": "45678",
"name": "Testing 1",
"testProgram": {
"testProgramSeq": "4567",
"name": "test25",
"spreadMethod": null,
"ul": false,
"ps": "2",
"somestatus": "distributed"
}
}
}
我上面有一个 JSON 显示。 我需要检查它是否具有 somestatus 属性,如果是,则检索其值
我已经尝试了以下方法,但它不起作用
if (test.hasOwnProperty('test.testProgram.somestatus')) {
alert('yes')
}
最佳答案
您可以split
字符串并使用reduce
循环遍历数组。如果没有找到,这将返回一个空对象。如果找到则返回该值。
let obj = {
"testPositionSeq": "12345",
"test": {
"testSeq": "45678",
"name": "Testing 1",
"testProgram": {
"testProgramSeq": "4567",
"name": "test25",
"spreadMethod": null,
"ul": false,
"ps": "2",
"somestatus": "distributed"
}
}
};
let key = 'test.testProgram.somestatus';
let result = key.split('.').reduce((c, v) => {
if (c.hasOwnProperty(v)) return c[v];
else return {};
}, obj);
console.log(result);
您可以将其缩短为:
let result = key.split('.').reduce((c,v)=> c[v] || {},obj);
关于jquery - 如何使用 hasOwnProperty 并在嵌套 JSON 中检索其值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50812671/