Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get part of JS object

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!

like image 328
Haris Krajina Avatar asked Jul 01 '14 21:07

Haris Krajina


People also ask

Can you filter an object JavaScript?

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.

How do I find the first item of an object?

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] .


2 Answers

Underscore.js has _.pick that does exactly that:

var new_obj = _.pick(obj, ['name', 'age']);
like image 140
Felix Kling Avatar answered Oct 23 '22 18:10

Felix Kling


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.

fiddle

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.

like image 34
royhowie Avatar answered Oct 23 '22 17:10

royhowie