0

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.

Justin Johnson
31.3k7 gold badges67 silver badges89 bronze badges
asked May 7, 2010 at 21:06
1
  • jsonArray is not an array, its an object - jsonArray.homes is one though. Commented May 7, 2010 at 23:19

3 Answers 3

5

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;
}
answered May 7, 2010 at 21:11
Sign up to request clarification or add additional context in comments.

1 Comment

+1 I was looking at this wondering how I used to do it in c# before linq :)
0

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);
} 
answered May 7, 2010 at 23:22

Comments

-2

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

answered May 7, 2010 at 21:22

1 Comment

You shouldn't use for..in to iterate over an array, but if you're going to, you need to at least check hasOwnProperty

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.