我想获取一个JSON / JavaScript对象的键名作为字符串。也许这很容易,但是我无法弄清楚。

我有这个对象(简化示例,有理由将键命名为字符串):

var obj = {
  "input1": {
    "type": "input",
    "value": "aaa"
  },
  "input2": {
      "type": "checkbox",
      "value": "bbb"
  }
}


现在我想做这样的事情:

currentInputName = getTheNameOfThisAsString(obj.input1);
console.log(currentInputName);  // output should be "input1"

currentInputName = getTheNameOfThisAsString(obj.input2);
console.log(currentInputName);  // now output should be "input2"


我正在尝试使用Object.keys()Object.getOwnPropertyNames(),但是都将typevalue返回给我,因此它们输出的是指定对象的键,而不是对象名称本身。

最佳答案

使用Object.keys()访问对象的键。



var obj = { "input1": { "type": "input", "value": "aaa" }, "input2": { "type": "checkbox", "value": "bbb" } };
var keys = Object.keys(obj);
console.log(keys);

关于javascript - Javascript/JSON:以字符串形式获取指定对象的名称,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48186195/

10-14 10:25
查看更多