I have an object:
person = {
birth_year: 1970,
first_name: "John",
last_name: "Doe",
occupation: "Doctor",
city: "Boston",
married: true
}
I have an array of key names in given order:
keys = ["occupation", "last_name", "city"]
I want to get this array:
["Doctor", "Doe", "Boston"]
It is important, that the answer should guarantee the order (JavaScript does not guarantee the order for object iteration).
I think there is probably some utility function in lodash/underscore to do it simply, but can't figure out any.
You can use Array.prototype.map
for this. Map loops through an array and creates a new array by applying a function to each item. When you use the keys
array as a starting point, and return the value in o
for that key, you'll get a new array with only values.
When using "dynamic" key names, you use a object[stringKeyName]
notation to retrieve a value.
var o = {
birth_year: 1970,
first_name: "John",
last_name: "Doe",
occupation: "Doctor",
city: "Boston",
married: true
};
var keys = ["occupation", "last_name", "city"];
var result = keys.map(function(k) { return o[k]; });
console.log(result);
If it fits your style, you can create a helper method to replace the anonymous function:
var o = { birth_year: 1970, first_name: "John", last_name: "Doe", occupation: "Doctor", city: "Boston", married: true };
var keys = ["occupation", "last_name", "city"];
var prop = obj => key => obj[key];
var result = keys.map(prop(o));
console.log(result);