Timnkd
Timnkd

Reputation: 1

How do I create an Array into another Array?

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.

Upvotes: 0

Views: 426

Answers (3)

Sean Kinsey
Sean Kinsey

Reputation: 38046

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);
}  

Upvotes: 0

charlie mac
charlie mac

Reputation: 1

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 } );

Upvotes: -2

Samir Talwar
Samir Talwar

Reputation: 14330

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;
}

Upvotes: 5

Related Questions