sharafjaffri
sharafjaffri

Reputation: 2214

How to update Array using $.each in jQuery

I have an array parsed using JSON.parse() given below.

var b = [{"pk":"1","name":"Ali","marked":"N" },
{"pk":"2","name":"Zeeshan","marked":"N" },
{"pk":"3","name":"Tariq","marked":"N" }]

This list contains roughly 4000 records, Now I want to update marked = "Y" where pk is in [2,3]. pk list length could be 100. My question is, how could we iterate over b and set marked="Y" where pk is in listed values ?

Upvotes: 3

Views: 9897

Answers (2)

zakhefron
zakhefron

Reputation: 1443

Try

var b = [
  {"pk":"1","name":"Ali","marked":"N" },
  {"pk":"2","name":"Zeeshan","marked":"N" },
  {"pk":"3","name":"Tariq","marked":"N" }
];
var condition = ["2", "3"];

$.each(b,function(index,value){
  if(condition.indexOf(value.pk) > -1){
     value.marked = "Y";
  }
});

console.log(b);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075925

No need for $.each in the modern world, arrays have forEach and such (which you can shim if you really need to support obsolete browsers like IE8).

If pk can have 100 entries and you're filtering 4,000 records, I'd build a map of pk values and use that. Here's an ES5 approach:

var b = [
  {"pk":"1","name":"Ali","marked":"N" },
  {"pk":"2","name":"Zeeshan","marked":"N" },
  {"pk":"3","name":"Tariq","marked":"N" }
];
var pk = ["2", "3"];

// Build the "map"
var map = Object.create(null);
pk.forEach(function(value) {
  map[value] = true;
});

// Mark relevant entries
b.forEach(function(entry) {
  if (map[entry.pk]) {
    entry.marked = "Y";
  }
});
console.log(b);

This avoids constantly calling pk.indexOf(entry.pk) to see if an entry should be marked, which requires re-scanning the array each time. Instead, it leverages the JavaScript engine's object property lookup code, which is highly optimized on modern browsers (even unoptimized it would likely be some kind of hash map or similar, but they optimize these days).

If you did want to use $.each instead, just change

pk.forEach(function(value) {

to

$.each(pk, function(_, value) {
// Note ------------^

and the same for the b loop later. $.each calls the callback with the index of the entry as the first argument, and then the value.

Upvotes: 1

Related Questions