In Lodash.js / Underscore.js, how do I add an index for each item?

Here is the input:

[{animal: "cat"}, {animal:"dog}}

      

And the output will be:

[{animal: "cat", idx: 1}, {animal: "dog", idx: 2}]

      

Does anyone have any ideas on how to do this in Lodash / Underscore.js?

+3


source to share


4 answers


In a substring:

You can use .map or .each to iterate over each element of the target array you wanted to add indices to. Then you can use _. Extend to add an idx prop.



Working example:

var data =  [{animal: "cat"}, {animal:"dog"}]

_.map(data, function(e, i) {
  return _.extend(e, {idx: i + 1});
});

      

+2


source


var data = [{animal: "cat"}, {animal:"dog"}, {animal:"er"}];
var data2 = _.select(data,function(val, key){    
    return {val, idx : key};
});

      



0


source


Loop through the items adding an index to each.

_.each(data, function(elt, i) { elt.idx = i + 1; })

      

0


source


var newAnimals = _.map(animals, function(animal, index){
    animal.idx = index + 1;
    return animal;
})

      

0


source







All Articles