使用父键,使用JavaScript Object / JSON

时间:2018-06-27 09:55:11

标签: javascript json

考虑以下objecT:

JSON

{
  "id1": {
    "key1": "valueX",
    "key2": "dont care"
  },
  "id2": {
    "key1": "valueY",
    "key2": "dont care"
  },
  "id3": {
    "key1": "valueZ",
    "key2": "dont care"
  }
}

考虑到父键(例如“ id2”),有没有办法返回受约束来自“ key1”的嵌套“ valueY”?

要清楚:

  • 输入:“ id2”
  • 输出:“ valueY”(在“ id2”中查找“ key1”)

3 个答案:

答案 0 :(得分:1)

您可能正在尝试执行以下操作:

let json = {
  "id1": {
    "key1": "valueX",
    "key2": "dont care"
  },
  "id2": {
    "key1": "valueY",
    "key2": "dont care"
  },
  "id3": {
    "key1": "valueZ",
    "key2": "dont care"
  }
}

valueFinder = (id, key) => json[id][key]

console.log(valueFinder("id2", "key1"))

答案 1 :(得分:0)

您可以通过这种方式获得:

 var data={"id1": { "key1": "valueX","key2": "dont care"},"id2": {"key1": "valueY","key2": "dont care" },"id3": { "key1": "valueZ", "key2": "dont care" }}, key="id2";
console.log(key + " = " + data[key].key1);
       

答案 2 :(得分:0)

如果您知道所需的键的名称始终为“ key1”(如示例中所示),则可以使用以下功能:

var obj = {
  "id1": {
    "key1": "valueX",
    "key2": "dont care"
  },
  "id2": {
    "key1": "valueY",
    "key2": "dont care"
  },
  "id3": {
    "key1": "valueZ",
    "key2": "dont care"
  }
};

var getFirstChild = function(obj, key) {
  return obj[key].key1;
}

alert(getFirstChild(obj, 'id2'));

首先获得具有指定键的对象,然后使用 key1 键搜索该对。

如果要获取对象的第一个键,无论其名称如何,都可以使用以下命令:

var obj = {
      "id1": {
        "key1": "valueX",
        "key2": "dont care"
      },
      "id2": {
        "key1": "valueY",
        "key2": "dont care"
      },
      "id3": {
        "key1": "valueZ",
        "key2": "dont care"
      }
    };

    var getFirstChild = function(obj, key) {
      return obj[key].key1;
    }

    alert(getFirstChild(obj, 'id2'));

这将再次搜索您指定的键,获取所有值,然后返回第一个。请注意,取决于javascript的实现,属性是在对象内部排序的。意味着您在代码中指定的第一个属性可能根本不是对象中的第一个属性。