mattts mattts - 6 months ago 7
Javascript Question

return object via array values

I have an object and would like to find and return the object values based on an array.

var profile = {
'firstName' : 'John',
'lastName' : 'Doe',
'mood' : 'happy'
};

var updated= ['firstName','mood'];


The updated array gets changed with the key when a the relevant field has been changed.

Thanks.

nem nem
Answer

I have an object and would like to find and return the object values based on an array.

You don't need underscore.js for this. You can do this with plain js simply by iterating over the array and extracting the necessary properties from your object:

var profile = {
  'firstName': 'John',
  'lastName': 'Doe',
  'mood': 'happy'
};

var updated = ['firstName', 'mood'];

updated.forEach(function(prop) {
  console.log(profile[prop]);
});

The updated array gets changed with the key when a the relevant field has been changed.

Not sure I understand you exactly, but it seems that you want an array of values for properties of the profile object whose names are contained in the updated array. Using Array.prototype.map would do the trick:

var profile = {
  'firstName': 'John',
  'lastName': 'Doe',
  'mood': 'happy'
};

var updated = ['firstName', 'mood'];

var values = updated.map(function(prop) {
  return profile[prop];
});

console.log(values);

Comments