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?
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.
You can use the $.map
function from jQuery :
var value = $.map(example, function () {
return this.name;
});
This will return an array of the items.
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