10

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}
});
5
  • Your question asks for the result to be an object with properties 0, 1 etc, however this looks a lot like an array - and most answers give you back an array not an object. What is it you actually want back? Commented Oct 12, 2012 at 9:56
  • This is not a jQuery object, it's a simple array... Commented Oct 12, 2012 at 9:58
  • @FelixKling - yes, but OP is using jquery .each to iterate over it. And why not? If you're using jQuery you're free to use each to iterate it. Commented Oct 12, 2012 at 9:59
  • @Jamiec: I'm not saying that one cannot use jQuery for this. OP originally wrote "I have this jQuery object" and I just wanted to clarify that it is a normal array of objects. It's not related to jQuery at all and using jQuery does not make everything a "jQuery object" or "jQuery array". That's all :) Commented Oct 12, 2012 at 10:01
  • @FelixKling - Ah I C. Didnt see (or perhaps didnt notice) the original wording. Commented Oct 12, 2012 at 10:26

5 Answers 5

13

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for the simplest solution if the OP actually wants an array rather than an object which pretends to be an array.
@Jamiec Added the alternative if the OP really wants an object.
This is not a one-liner if you have automatic code-formatting.
7
var newObj = {};
$.each([{'prop': true}, {'prop': false}], function (i, o) {
    newObj[i] = o.prop;
});

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

Comments

1

First off, that's just native JS, there's no jQuery needed here.

var startObj = [{'prop': true}, {'prop': false}],
    endObj = [], // This could also be {} if you want but if you just have an array in startObj, it doesn't make much sense
     i = 0,
     i_max = startObj.length;

for (i; i < i_max; i++) {
    endObj.push( startObj[i].prop );
    // if you changed endObj to be {} then use the following line instead of the one above
    // endObj[i] = startObj[i].prop;
}

Comments

0

You're not really creating an object here, but an array:

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

But to avoid globals, you might want to use a IIFE:

var newObj = (function()
{//takes any amount of objects as argument
    var returnArray = [];
    var argumentsToArray = Array.prototype.slice.apply(arguments,[0]);//create array of objects passed
    $.each(argumentsToArray, function (i, o)
    {
        returnArray[i] = o.prop
    });
    return returnArray;//is assigned to newObj
})({'prop': true}, {'prop': false});//1 obj, 2, 3, 4, 5... doesn't matter

4 Comments

How does the first snippet have globals that the second avoids? It appears to be exactly the same to me, why do you make it so complicated?
It's not really globals in this case, but there's more ways you can go with an IIFE in a case like this: wrap it in a callable function, and pass a property name/property names, pass as many object as you like,... this snippet can't do those things yet, sure, but it won't require that much effort to implement new features this way (IMO)
Ok... it sounded like the first snippet had a major drawback which you tried to compensate in the second snippet. Btw, I don't think you need to convert arguments into a proper array, I think jQuery can handle array-like objects properly.
@FelixKling: I haven't tested the code, I wasn't entirely sure so I went for the safer route... And maybe someone might see this and discover arguments isn't an array, so I figured best to include that line. Just tested in console, arguments is processed just fine
-3
var obj = "{";
$.each([{'prop': true}, {'prop': false}], function (index, o) {
    obj += '"' + index  + '":'  + o.prop + ",";
});
var newObj = obj.substring(0, obj.length - 1);
newObj += "}";
console.log(newObj);
console.log($.parseJSON(newObj));
​

8 Comments

I would say too dirty to post ;)
Yup its dirty. But its a solution. So It can take place. :)
Uh... please never ever do something like this... I'm actually inclined to downvote this, since it is not useful IMO.
sure. Knowledge is worth sharing. I don't know the other solution. Now I also gained knowledge from this. Thanks
I don't get this solution - why would you ever want to do this by string-mashing +parsing that string?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.