Search code examples
javascriptlodash

lodash: iterate each object and get its key


I am confused by a testing output from my lodash source code:

My task is to get the keys of an map, which include multiple objects. For some reason, I need to loop through the map and get the object. Below is my source code:

var results = {"1":[1,2,3],"2":[2,4,6]};
var out = _.map(results, (result) => {
  //console.log(result);
  let key = _.keys(result);//I expect the key to be 1 or 2
  //... doing something else with the value, I assume is [1,2,3] or [2,4,6]
});
console.log(out);

I was expecting my result to be {'1': [ 1, 2, 3 ]} or {'2': [ 2, 4, 6 ]} so that I can get the key of 1 or 2, in my iteration. But what I got was that the result is [1,2,3] or [2,4,6] and the keys I got was [ undefined , undefined].

I am really confused about the result. Can someone interpret that? Thanks!


Solution

  • Use _.keys()

    var results = {"1":[1,2,3],"2":[2,4,6]};
    var out = _.keys(results, (result) => {
      console.log(result);
      //... doing something else
    });
    
    console.log(out);
    <script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>