Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract each value of a single property from an array of objects in jQuery

I need to create a new object iterating over an array of objects which initially looks like this:

startObj = [{'prop': true}, {'prop': false}];

I would like the result to be:

endObj = {0: true, 1: false}

I was thinking to use $.each but then I don't know how to proceed from here. Any hints?

$.each([{'prop': true}, {'prop': false}], function (i, o) {
    var newObj;
    // the new object should look like this
    // newObj = {0: true, 1: false}
});
like image 706
js999 Avatar asked Oct 12 '12 09:10

js999


Video Answer


2 Answers

Here's a one-liner.

var newObj = $.map(oldObj, function(val) { return val.prop; });

jsFiddle.

If the OP really wants an object (or rather, doesn't want an array)...

var newObj = $.extend({}, $.map(oldObj, function(val) { return val.prop; }));

jsFiddle.

like image 190
alex Avatar answered Oct 13 '22 00:10

alex


var newObj = {};
$.each([{'prop': true}, {'prop': false}], function (i, o) {
    newObj[i] = o.prop;
});

Live example: http://jsfiddle.net/8X48q/

like image 40
Jamiec Avatar answered Oct 12 '22 23:10

Jamiec