3

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 ?

3
  • 1
    That's not JSON. JSON is a textual notation for data exchange. If you're dealing with JavaScript source code, and not dealing with a string, you're not dealing with JSON. Commented Jun 20, 2016 at 12:05
  • I have shown parsed array. Commented Jun 20, 2016 at 12:07
  • Yes, but the point is by the time you're marking those entries, you're not dealing with JSON, so JSON is irrelevant to the question. Commented Jun 20, 2016 at 12:13

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.