-2

Is it possible to query a range of objects for a specific value before you do anything with it? For example, I will be getting a JSON structure similar to below with a set of properties:

"Properties": [
  {
    "Name": "product",
    "Values": [ "Jacket", "Shirt", "Trousers" ]
  },
  {
    "Name": "color",
    "Values": [ "Red", "Blue", "Green" ]
  }
]

Once I've loaded the JSON in my JS, I would like to be able to ask something like "go through each object in the array - if Name equals 'product', do something, if Name equals 'color', do something else" and so on.

I was thinking it would be something similar to the below, but so far no luck. I'm guessing it's because I'm trying to query a value in a child of Properties.

if (Properties.hasOwnProperty('Name') === "product") {
    alert('Yes');
} else {
    alert('No');
}

Predictably, the above snippet is returning "No" even when a Name property has the value "product".

nimaek
  • 214
  • 2
  • 9

2 Answers2

1

I would like to be able to ask something like "go through each object in the array - if Name equals 'product', do something, if Name equals 'color', do something else" and so on.

You're describing a loop, and then branching within the loop. There are a dozen ways to loop through an array in JavaScript (this answer covers most if not all of them). One of those is forEach.

For the branch, you'd typically use if or switch although there are many options for that, too.

So for instance, one possible way is to use forEach and switch:

Properties.forEach(function(property) {
    switch (property.Name) {
        case "product":
            // ...
            break;
        case "color":
            // ...
            break;
    }
});
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • @Seabizkit: There's no particular reason for the overhead of adding that `hasOwnProperty` call. All of the OP's objects have it, and the effect of *not* having it is just that it doesn't match anything in the `switch` (not, for instance, an error). – T.J. Crowder Oct 06 '15 at 08:48
1

Try this (pure js):

Properties = [
    {
        "Name": "product",
        "Values": [ "Jacket", "Shirt", "Trousers" ]
    },
    {
        "Name": "color",
        "Values": [ "Red", "Blue", "Green" ]
   }
];
for (i = 0; i < Properties.length; i++) { 
    var p = Properties[i];
    if (p.hasOwnProperty('Name') && p.Name == "product") {
        console.log('Yes');
    } else {
        console.log('No');
    }
} 
Alex Tartan
  • 6,736
  • 10
  • 34
  • 45