views:

91

answers:

3

I have the following JavaScript Array:

var jsonArray = { 'homes' : 
[
    {
        "home_id":"203",
        "price":"925",
        "sqft":"1100",
        "num_of_beds":"2",
        "num_of_baths":"2.0",
    },
    {
        "home_id":"59",
        "price":"1425",
        "sqft":"1900",
        "num_of_beds":"4",
        "num_of_baths":"2.5",
    },
    // ... (more homes) ...     
]}

I want to convert this to the following type of Array (pseudo code):

var newArray = new Array();
newArray.push(home_id's);

How can I do that?

Notice how the newArray only has home_ids from the big jsonArray array.

+5  A: 

Just make a new array and copy the old values in.

var ids = [];
for (var i = 0; i < jsonArray.homes.length; i++) {
    ids[i] = jsonArray.homes[i].home_id;
}
Samir Talwar
+1 I was looking at this wondering how I used to do it in c# before linq :)
DannyLane
A: 

Here's one iterative way:

function getPropertyValues (array, id) {
  var result = [];
  for ( var hash in array ) {
    result.push( array[hash][id]);
  }
  return result;
}

var home_ids = getPropertyValues(jsonArray.homes, "home_id");

Or if you want to do it real quick and dirty (and you are only targeting modern Javascript capable engines):

var home_ids = jsonArray.homes.map( function(record) { return record.home_id } );

charlie mac
You shouldn't use `for..in` to iterate over an array, but if you're going to, you need to at least check `hasOwnProperty`
Justin Johnson
A: 

Again, jsonArray is not an array but an object, but jsonArray.homes is

var arr = [];
for (var i=0, len = jsonArray.homes.length; i < len; i++){
    arr.push(jsonArray.homes[i].home_id);
}  
Sean Kinsey