Ezeewei Ezeewei - 1 month ago 6
Javascript Question

can you get var name from object with nested objects with lodash?

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

RESOLVED VERSION:
https://jsfiddle.net/adamchenwei/Lyg2jy61/10/

For some reason findKey for parent top level got

undefined

My objective is to get the result = 'myName' with lodash;



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>




Answer

It looks like what you're actually trying to do is get the first key of an object. To get the keys of an object, you can use _.keys. Then just retrieve the first one.

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>

Comments