Not sure if the title of the question is doing it justice, but here is an example. I have object:
var plumber = {
name: 'Mario',
age: 42,
game: 'Super Mario'
}
I am looking for an elegant way of using either jQuery
or Undescore
to get key and value from this object.
// foo() would be desired elegant function
plumber.foo('name')
#> { name: 'Mario' }
// or even better
plumber.foo(['name','age'])
#> { name: 'Mario', age: 16 }
Thank you!
JavaScript's Objects are not iterable like arrays or strings, so we can't make use of the filter() method directly on an Object . filter() allows us to iterate through an array and returns only the items of that array that fit certain criteria, into a new array.
To access the first property of an object, pass the object to the Object. values method and access the element at index 0 , e.g. Object. values(obj)[0] .
Underscore.js has _.pick
that does exactly that:
var new_obj = _.pick(obj, ['name', 'age']);
I think you could approach this two ways (without either of those two libraries). You can either pass the function an array of keys or you could pass it a variable number of arguments.
Using an array
var plumber = {
name: 'Mario',
age: 42,
game: 'Super Mario'
}
var splitObject = function (obj, keys) {
var holder = {};
keys.forEach(function (d) {
holder[d] = obj[d];
})
return holder;
}
var example = splitObject(plumber, ["name", "age"]);
console.log("example #1", example);
Using a variable number of arguments
var variableArguments = function (obj) {
var keys = Array.prototype.slice.apply(arguments).slice(1),
holder = {};
keys.forEach(function (d){
holder[d] = obj[d];
})
return holder;
}
var example2 = variableArguments(plumber, "name", "age");
console.log("example #2", example2);
Underscore.js
probably has its own function for this. You'd have to check the documentation.
edit:
pick is probably the most appropriate function, as per the comments above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With