1

I am trying to create a new array with just the object values of myArray. My code below returns newArray with both Objects stored, but I am stuck on how to get the 'values' out and put them into the array. I am used to for-in on Objects, but not sure how to access objects when they are stored in an Array.

var myArray = [{first: 'michael', last: 'jordan'}, {first: 'brett', last: 'favre'}];
var myFunc = function (values) {
    newArray = [];
    for (var i = 0; i < values.length; i += 1) {
        newArray.push(values);
    }
    return newArray;
}
2
  • What's the expected output? [ 'michael', 'jordan', 'brett', 'favre' ]? Commented Jan 2, 2014 at 3:06
  • jsfiddle.net/wvg8H Commented Jan 2, 2014 at 3:22

3 Answers 3

4

Try this:

var myFunc = function (values) {
    newArray = [];
    for (var i = 0; i < values.length; i += 1) {
        for(var e in values[i]) {
            newArray.push(values[i][e]);
        }
    }
    return newArray;
}

Demonstration

Note that this method is 'shallow'—that is, it will only get values one-level deep. If you had a structure like [{foo:{bar:'baz'}}], the result would be [{bar:'baz'}].

Sign up to request clarification or add additional context in comments.

2 Comments

I see that working, thank you. Do I always need to write a for-in loop to get access to the objects in an array?
@jstone Um no, if you know ahead of time what the properties you want to get are, you could have just done newArray.push(values[i].first, values[i].last) instead of that entire inner loop.
3

Consider this example.

var array = ['a','b','c','d'];

The index of 'a' is 0
The index of 'b' is 1
and so forth...

Therefore:

array[0] = 'a'



Next example:

var array = [ { foo: 'bar' }, { hello: 'world' } ];

The index of the first object is 0
The index of the second object is 1

Therefore:

array[0] = { foo: 'bar' }

To access a property of that object, you can do this:

array[0]['foo'] = 'bar';



So, you can do something like this, to iterate over the members of an object, when that object is inside of an array:

var array = [ { foo: 'bar' }, { hello: 'world' } ],
    newArray = [];

var i, len = array.length;

for( i=0; i<len; i++ ) {

    for ( e in array[i] ) {

        newArray.push(array[i][e]);

    }

}

OUTPUT: newArray = ['bar', 'world'];

Comments

1

This example uses the relatively new Object.keys() and Array.reduce():

var values = myArray.reduce(function(prev, current) {
    return prev.concat(Object.keys(current).map(function(key) { 
        return current[key]; 
    }));
}, []);

Comments

Your Answer

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.