jquery - 如何使用 hasOwnProperty 并在嵌套 JSON 中检索其值

标签 jquery

{
    "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')
}

https://jsfiddle.net/o2gxgz9r/48809/

最佳答案

您可以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/

相关文章:

javascript - 将 javascript 按钮更改为在任何地方单击

jquery - 使用 jQuery UI 拖动旋转且绝对定位的 div

javascript - 使用 Javascript 或 jquery 的多语言页面

javascript - 更改包含在 <td> 标记中的某些值的字体颜色

javascript - 在水平进度条上 Bootstrap 多个条

jquery - 在 Gulp 中 bundle jquery 和 Bootstrap

php - 多次循环 jQuery .post 函数

php - 使用 jQuery AJAX 在完整日历中显示事件

javascript - 以特定间隔将图像插入 DOM

javascript - 无法使用ajax序列化功能将图像插入数据库