Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Lodash.js/Underscore.js, how to add index for every element?

Here is the input:

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

And the output would be :

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

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

like image 251
Hanfei Sun Avatar asked Nov 28 '25 11:11

Hanfei Sun


1 Answers

In Underscore:

You could use either .map or .each to iterate across every element in the target array you were looking to add indexes to. Then you could use _.extend to add the "idx" prop.

Working Example:

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

_.map(data, function(e, i) {
  return _.extend(e, {idx: i + 1});
});
like image 159
Pavan Ravipati Avatar answered Dec 01 '25 01:12

Pavan Ravipati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!