views:

30

answers:

2

How can you query an object with an array?

var myArray = ['A','C']

Using myArray, how can I get a returned array with ['1','3'] out of the following (previously JSON object) (without using a third party query script -- unless it's jQuery :)

[ { "property1": "1", 
    "property2": "A"
   },
  { "property1": "2", 
    "property2": "B"
   },
  { "property1": "3", 
    "property2": "C"
   } ]
+3  A: 

You could a nested loop:

var myArray = ['A','C'];
var json = [{ 
    'property1': '1', 
    'property2': 'A'
}, { 
    'property1': '2', 
    'property2': 'B'
}, { 
    'property1': '3', 
    'property2': 'C'
}];

var result = new Array();
for (var i = 0; i < myArray.length; i++) {
    for (var j = 0; j < json.length; j++) {
        if (json[j].property2 === myArray[i]) {
            result.push(json[j].property1);
        }
    }
}

// at this point result will contain ['1', '3']
Darin Dimitrov
Darin!! Sweet solution! Thank you for my '1' and '3' :D
Emile
+1  A: 

You can walk the array like this:

var json = [ { "property1": "1", 
    "property2": "A"
   },
  { "property1": "2", 
    "property2": "B"
   },
  { "property1": "3", 
    "property2": "C"
   } ];

var myArray = ['A', 'C']; // Here is your request
var resultArray = []; // Here is the container for your result

// Walking the data with an old-fashioned for loop
// You can use some library forEach solution here.
for (var i = 0, len = json.length; i < len; i++) {
    var item = json[i]; // Caching the array element

    // Warning! Not all browsers implement indexOf, you may need to use a library
    // or find a way around
    if (myArray.indexOf(item.property2) !== -1) {
        resultArray.push(item.property1);
    }
}

console.log(resultArray);
Igor Zinov'yev
+1 thanks Igor for this solution! seems to be a good alternative solution.
Emile
It's really not an alternative :) It's the same except for the `indexOf` part. I'm really surprised how close it is to Emile's answer, because I didn't see his solution prior to answering this question.
Igor Zinov'yev