1

Friends I have following like json array

[
   {
      "Rate":100.0,
      "MaterialID":"BOLT",
      "BrandName":"",
      "Description":"",
      "Unit":"KG",
      "TokenNumber":2
   },
   {
      "Rate":null,
      "MaterialID":"PLYWOOD",
      "BrandName":"",
      "Description":"",
      "Unit":"FT",
      "TokenNumber":2
   },
   {
      "Rate":null,
      "MaterialID":"SCREW 1.5 INCH",
      "BrandName":"",
      "Description":"",
      "Unit":"KG",
      "TokenNumber":2
   }
]

I want to know the shortest way to find an element that has materialID with value PLYWOOD.
I can do it using for loop. But I want to know some shortcut for this something like

var unit = jsonArray[<whiere materialID == 'PLYWOOD']['Unit'];

You can use jQuery if required.

shashwat
  • 7,851
  • 9
  • 57
  • 90

3 Answers3

5

You may use $.grep

http://api.jquery.com/jQuery.grep/

closure
  • 7,412
  • 1
  • 23
  • 23
2

jQuery is not required, so you could do it like this:

function findItem(arr, key, value) {
    for (var i = 0; i < ARR.length; i++) {
       if (arr[i][key] === value) {
           return(i);
       }
    }
    return(-1);
}

var plywoodIndex = findItem(data, "MaterialID", "PLYWOOD");
if (plywoodIndex !== -1) {
    // do something with the plywoodIndex object here
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

As Raghaw has suggested. I find the way to do my work. I designed following function that can return the object with specified materialID.

Assumptions: materials is the array

function getMaterialFromArray(materialID) {
    return $.grep(materials, function (n, i) {
        return(n.MaterialID == materialID);
    })[0];
}
shashwat
  • 7,851
  • 9
  • 57
  • 90