1

I keep getting eluded by how property values should be properly retrieved from array literals.

Object literal:

var obj = {
    "p1": "v1",
    "p2": "v2",
    "p3": "v3"
};

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        console.log(key + " -> " + obj[key]);
    }
}

Console log output:

p1 -> v1
p2 -> v2
p3 -> v3

Array literal:

var obj = [
    { "pa":"va1", "pb":"vb1" },
    { "pa":"va2", "pb":"vb2" },
    { "pa":"va3", "pb":"vb3" },
    { "pa":"va4", "pb":"vb4" }
];

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        console.log(key + " -> " + obj[key]);
    }
}

Console log output (duh!):

0 -> [object Object]
1 -> [object Object]
2 -> [object Object]
3 -> [object Object]

What I'm trying to do: check if a string matches one of the pa values. If it does, do something.

This would be the logic:

var myString = "a value I'm getting from somewhere else ;)"
if (myString == any of the pa values) {
    // do something
}

Any help appreciated!

Wallace Sidhrée
  • 11,221
  • 6
  • 47
  • 58

4 Answers4

4

Using the filter method (link contains code to add functionality to older browsers - IE8 and older) and then check the length of the resulting array:

var obj = [
    { "pa":"va1", "pb":"vb1" },
    { "pa":"va2", "pb":"vb2" },
    { "pa":"va3", "pb":"vb3" },
    { "pa":"va4", "pb":"vb4" }
];

var filtered = obj.filter(function(element) { 
    return element.pa === myString;
});

if (filtered.length > 0) {
   // contains string
}

JS Fiddle

Richard Dalton
  • 35,513
  • 6
  • 73
  • 91
2

obj is not a object as you expect, it's an array of objects. You'll need to iterate the array and then iterate the keys in each array item.

var i, key;

for (i = 0; i < obj.length; i++) {
  for (key in obj[i]) {
    if (obj[i].hasOwnProperty(key) {
      console.log(key + " -> " + obj[i][key]);
    }
  }
}
JaredMcAteer
  • 21,688
  • 5
  • 49
  • 65
0

If you don't need to know the parent, there may be a performance boost in not looping through it all (depending on array and object sizes). This will also remove the need to change your code if another nested level of objects is added.

JSON.stringify(obj).indexOf(':"pa1"')>-1

JSON.stringify() turns your array into a string like this:

"[{"pa":"va1","pb":"vb1"},{"pa":"va2","pb":"vb2"},{"pa":"va3","pb":"vb3"},{"pa":"va4","pb":"vb4"}]"

Which we can then of course just do a normal textual search through

JSON.stringify() is supported for IE8 and above

MDEV
  • 10,730
  • 2
  • 33
  • 49
0

This may be oversimplifying, but if you just want to know if you have a string in mystring that is an item in the array, the array can be addressed as indexed by strings.

Update - I ran this through firebug and discovered I had my notation incorrect for this method to work the way I thought it should - namely as a referable list of objects or values by label.

var obj = [];
obj["val1"] = "pa";
obj["val2"] = "pb";

mystring="val1";

if (obj[mystring]){
   alert ('object exists in array');
}
else{
    alert('object with index ' + mystring + ' does not exist');
}

No looping required, though your array setup has to change to support this sort of "look up" approach.

J E Carter II
  • 1,436
  • 1
  • 22
  • 39
  • Thanks for the time you put into this, but I'm not getting why you've inverted `"val1: "pa"`. Property precedes value... Moreover your example is just a simple object literal, not an array (which was part of the problem). But cheers for the contribution! – Wallace Sidhrée Sep 12 '13 at 15:30
  • You're welcome. The inversion literally turns the problem of finding a value on an object in an array on its head. pa above could be an object unto itself, here I have just a string. By creating the array this way, you create an indexed list of objects so you can look-up objects by name simply by reference. I find this sort of thing useful as an associative entity / hash map sort of arrangement. In my example I just looked to satisfy the "does it exist" question, but you could use this more robustly. – J E Carter II Sep 12 '13 at 15:39
  • Interesting take on it. I'll be revisiting your method later. Cheers! – Wallace Sidhrée Sep 12 '13 at 15:43