Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array of property values from array of objects with jquery [duplicate]

I am trying to get from here:

example = [{
  name: "someone1",
  city: "somewhere1",
  state: "someplace1"
},{
  name: "someone2",
  city: "somewhere2",
  state: "someplace2"
}]

to here:

example.name = [ "someone1", "someone2" ]

In as little a code as possible. Obviously I could just loop it and build the array but I need to do this a large number of times on a variety of objects. I could write a function to do it but it would be difficult to make the function general enough for my application.

Is there a shortcut for this in jQuery?

like image 531
awimley Avatar asked Apr 06 '15 13:04

awimley


2 Answers

I made a quick test for you here: http://jsperf.com/jquery-vs-javascriptlvjsklvjsfklsfklsdjfk

It consists of three solutions:

A basic for loop

for (var i = 0; i < example.length; i++) {
    array.push(example[i].name);
}

A jQuery $.each()

$.each(example, function(i, item) {
    array.push(example[i].name);
});

And one answer posted to this thread

Object.keys(example).forEach(function(key) {
  //get the value of name
  var val = example[key]["name"];
  //push the name string in the array
  array.push(val);
});

Here are the results (bigger bar is better)

Basically what you have to keep in mind is that jQuery might have a shortcut which consists of "less code", but in reality it'll have worse performance than if you wrote the code yourself.

like image 91
m0meni Avatar answered Sep 21 '22 15:09

m0meni


You can use the $.map function from jQuery :

var value = $.map(example, function () {
    return this.name;
});

This will return an array of the items.

like image 35
Sherif Ahmed Avatar answered Sep 20 '22 15:09

Sherif Ahmed