nachocab
nachocab

Reputation: 14374

How to access multiple properties of a javascript object?

If I have the array:

my_array = [{a:3,b:4,c:7},{a:5,b:8,c:6}]
property_names = ["a","c"]

How can use the property_names array against my_array to get the following output?:

subset_array = [[3,7],[5,6]]

Upvotes: 1

Views: 14230

Answers (3)

Sirko
Sirko

Reputation: 74076

You can access the properties by two notations:

Either o.a and o.c or o['a'] and o['c'].


EDIT

If you want to create a new array containing both values, then just do so using, e.g, the code suggested by @Reid :

[o.a, o.c]

2nd EDIT

So just build your array up inside the map function like the following:

var filter = [ "a","c","f","zzz"]; // should

subset_array = my_array.map( function(v){ var newArr = [];

for( var i=0; i<filter.length; ++i ) {
  if ( typeof v[ filter[i] ] !== 'undefined' ) {
    newArr.push( v[ filter[i] ] );
  }
}

return newArr;

} );

One thing to note is, however, that as long as you use primitive types (like the int values in the example) the above code will clone the properties. This means, if you change a value in my_array at some point, subset_array will not be changed implicitly, but you have to recreate subset_array or adjust the value there, too.

Upvotes: 4

ThiefMaster
ThiefMaster

Reputation: 318518

var my_array = [{a:3,b:4,c:7}, {a:5,b:8,c:6}];
var keys = ['a', 'c'];

my_array.map(function(d){
    return keys.map(function(k) {
        return d[k];
    });
});

This will give you [[3, 7], [5, 6]] and seems to be just what you want.


[Obsolete initial answer; before the OP updated his question]

Use o.a and o.c - no magic involved and no kittens harmed!

You could also use the [] syntax: o['a'] and o['c'] - but usually you only use it if you want to access a dynamic property name (i.e. a variable instead of a quotes string inside the [])


If you want an array with both values:

var a_and_c = [o.a, o.c];

Now you can use a_and_c[0] and [1] to access those two values.

Upvotes: 9

user166390
user166390

Reputation:

This is not a full answer, however I believe it will be of use:

var values = []
var obj = {a: 1, b: 2, c: 3}
for (var prop in obj) {
  if (obj.hasOwnValue(prop)) { // skip props in [[prototype]], no effect here
    values.push(obj[prop])
  }
}
values // -> [2, 1, 3] (in SOME UNDEFINED ORDER)

Key points:

  1. Iterate [all] object property names for the object (but not [[prototype]] chain)
  2. Access value dynamically from property name
  3. Properties are not ordered; sort values if needed, for instance

This can be expanded to add different "exclusion" rules, for instance. It can also be adapted to different higher-order functions.

Happy coding.

Upvotes: 1

Related Questions