kishan
kishan

Reputation: 466

how can i utilize closure in my code?

I have a JSON like that :

[
   {"data":"a"},
   {"data":"b"},
   {"data":"c"}
]

Using JavaScript, I want to add an incremental id field like that:

[
   {"data":"a","id":"xx_1"},
   {"data":"b","id":"xx_2"},
   {"data":"c","id":"xx_3"}
]

but I want to utilize JavaScript closure for

var cnt

in my following code how can I do that?

var data=[
    {"data":"a"},
    {"data":"b"},
    {"data":"c"}
    ];
    var cnt=0;
    data.map(function(data){
       data.id="xx_"+cnt;
       cnt++;
    })

console.log(data);

Upvotes: 1

Views: 49

Answers (3)

Andreas Louv
Andreas Louv

Reputation: 47099

No need to use .map since you only modify the objects in the array. Use .forEach((value, index) => {})

var data = [
  {"data":"a"},
  {"data":"b"},
  {"data":"c"}
];

data.forEach(function(obj, index) {
    obj.id = 'xx_' + (index + 1);
});

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68393

check this fiddle

var data=[
        {"data":"a"},
        {"data":"b"},
        {"data":"c"}
];
var counter = (function () { //this is a closure that will return an incremented count value everytime it is called
  var count = 1; // you can initialize to a different value if you want
  return function () {return count += 1;}
})();
data.map(function(data){
  data.id="xx_"+counter(); //calling the counter method
});
console.log(data);

Upvotes: 0

Oleksandr T.
Oleksandr T.

Reputation: 77482

In .map callback second argument is index so you can use it and don't use unnecessary variable cnt, like this

var data = [
  {"data":"a"},
  {"data":"b"},
  {"data":"c"}
];

data = data.map(function (element, index) {
  element.id = 'xx_' + (index + 1);
  return element;
});

console.log(data);

Upvotes: 3

Related Questions