如何在JavaScript对象中获取这些密钥

如何在JavaScript对象中获取这些密钥,javascript,underscore.js,lodash,Javascript,Underscore.js,Lodash,我的目标如下: var input = { "document": { "people":[ {"name":"Harry Potter","age":"18","gender":"Male"}, {"name":"hermione granger","age":"18","gender":"Female"} ] } } 我喜欢这样: _.ea

我的目标如下:

var input = {
        "document": {
            "people":[
                {"name":"Harry Potter","age":"18","gender":"Male"},
                {"name":"hermione granger","age":"18","gender":"Female"}
            ]
        }
    }
我喜欢这样:

_.each(result.document[people], function(item){
    console.log(item); 
    //What should I do here ? or I come wrong way ?
});
在我得到的项目中:

{name : 'Harry Potter', age : '18':, gender:'Male'}
{name : 'hermione grange', age : '18':, gender:'Female'}
我想知道[姓名、年龄、性别]。我该怎么办?

像这样的事情

_.each(result.document[people], function(item) {
  _.each(item, function(item, key) {
    console.log(key);
 });
});

_。对于对象,每个都会向回调函数发送第二个键参数。

给你。。最后的答案。根据注释编辑以返回键而不是值

_.each(result.document[people], function(item){
    //get keys as numerical array
    var num_arr = [];
    for (var key in item) {
        num_arr.push( key );
    }
    console.log(num_arr); // should return ['name', 'age', 'gender']

});

好的,现在我知道你实际上想要的是对象的名称,而不是值。所以我为您添加了另一个代码。 很抱歉,我现在没有时间解释,但我编写的这段代码确实做到了您需要的技巧

这将显示对象的名称:

root_obj=input.document.people[0];
tmp=[];
for(val in root_obj )
{
  tmp.push(val);
}
console.log(tmp);
root_obj=input.document.people;

for(obj in root_obj )
{
  tmp=[];
  for(val in root_obj[obj] )
  {
    tmp.push(root_obj[obj][val]);
  }
  console.log(tmp);
}
这显示了对象的值:

root_obj=input.document.people[0];
tmp=[];
for(val in root_obj )
{
  tmp.push(val);
}
console.log(tmp);
root_obj=input.document.people;

for(obj in root_obj )
{
  tmp=[];
  for(val in root_obj[obj] )
  {
    tmp.push(root_obj[obj][val]);
  }
  console.log(tmp);
}

如果您认为您的值是动态的,请首先使用函数

var input = {
    "document": {
        "people":[
            {"name":"Harry Potter","age":"18","gender":"Male"},
            {"name":"hermione granger","age":"18","gender":"Female"}
        ]
    }
}

var func = function (one, two) {
  var array = input[one][two];
  var arr =[];
  for (var i=0; i<array.length; i++){
     arr = Object.keys(array[0]);
  }
 return arr;       
}
func("document", "people"); // will return ["name", "age", "gender"]
试试这个

var s = {name: "raul", age: "22", gender: "Male"}
   var keys = [];
   for(var k in s) keys.push(k);

在这里,keys数组将返回您的键[name,age,gender]

遍历input.document.people。是否查找与键name,age和gender关联的值?在_每次这样的尝试中,您都可以得到它console.log[item.name,item.age,item.gender]Object.keysinput.document.people[0]?我想动态执行。所以我不想用“.”来限制内部。你已经问了完全相同的问题。另一个答案对你没有帮助吗?我想要的是[‘姓名’、‘年龄’、‘性别’]而不是价值观。你有其他的方法吗?