你可以从具有lodash的嵌套对象的对象中获取var名称吗?

时间:2016-10-07 15:54:48

标签: javascript object lodash

https://jsfiddle.net/adamchenwei/Lyg2jy61/7/

已解决的版本: https://jsfiddle.net/adamchenwei/Lyg2jy61/10/

出于某种原因{父母顶级findKey获得undefined 我的目标是使用lodash;

获得result ='myName'

    var obj = {
    	myName: {
      	Adam: 'Man',
      },
      herName: {
      	Eve: 'Woman',
      },
    };
    
    var result = _.findKey(obj, '0'); //as you can see somehow its undefined!
    
    var result2 = _.findKey(obj.myName, '0');
    
    console.log(result);//objective is to get the result = 'myName' with lodash;
    
    console.log(result2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

2 个答案:

答案 0 :(得分:2)

看起来你实际上要做的就是获取对象的第一个键。要获取对象的键,可以使用_.keys。然后只需检索第一个。

var obj = {
  myName: {
    Adam: 'Man',
  },
  herName: {
    Eve: 'Woman',
  },
};

console.log(_.keys(obj)[0]);

// Or if you want to do it exclusively with lodash functions
console.log(_.first(_.keys(obj)));

// or
console.log(_.head(_.keys(obj)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

答案 1 :(得分:1)

目前尚不清楚你到底发生了什么,但在你发布的对象上使用_.findKey会像这样:

https://jsfiddle.net/Lyg2jy61/8/

var obj = {
    myName: {
        Adam: 'Man',
    },
    herName: {
        Eve: 'Woman',
    }
};

console.log(_.findKey(obj, function(o) { return !!o.Adam; }));

如果您只想要第一个键:_.keys(obj)[0]