Imagine having a JavaScript object structured like this:
var x = {
'one': 1,
'two': 2,
'three': 3
}
Now, suppose you have an array containing the specific keys you want to access from this object.
Here are the keys you're interested in:
var keys = ['one', 'two'];
When you use these keys to extract information from the object, the desired output would be:
{
'one': 1,
'two': 2
}
In your hypothetical code snippet, you envision something like this:
var x = {
'one': 1,
'two': 2,
'three': 3
}
var keys = ['one', 'two'];
var answer = x[keys];
However, as you already know, this approach doesn't work...
Is there an elegant way in javascript to achieve this? Can an array be used to index multiple properties of an object efficiently?
You might consider a for-loop
solution that involves brute force, but is there perhaps a more sophisticated JavaScript feature that you're not aware of?
Any thoughts on this dilemma?