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}
});
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.
var newObj = {};
$.each([{'prop': true}, {'prop': false}], function (i, o) {
newObj[i] = o.prop;
});
Live example: http://jsfiddle.net/8X48q/
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