0

I wish to create a new array that contains objects from another Object

This was my try:

var obj =  {
    a:{},
    b:{}
}

var arr = new Array().concat(obj,[]);

Sadly, this is returning an array like this:

Array[1]
0: Object
    a: Object
    b: Object

The desired array, however, should look like this:

Array[2]
    0: Object
        a: Object
    1: Object
        b: Object

How could i achieve that in the shortest possible way, without having to loop the object?

7
  • 1
    Could you show what the desired end result should look like? Commented May 17, 2014 at 8:53
  • 1
    Do you mean you want var arr = [obj.a, obj.b]; ? Commented May 17, 2014 at 8:56
  • 1
    Well, the question says you want [{a: obj.a}, {b: obj.b}]. Commented May 17, 2014 at 8:57
  • 2
    "without having to loop the object" --- what is the technical reason for avoiding explicit loops in the code? Commented May 17, 2014 at 8:59
  • 2
    Could you explain what problem you're trying to solve by turning the object into an array? This sounds like an XY problem. Commented May 17, 2014 at 9:03

1 Answer 1

2

Here is an example without explicit loops:

var r = Object.keys(obj).map(function(key) {
    var o = {};
    o[key] = this[key];
    return o;
}, obj);

http://jsfiddle.net/zNh3G/

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

Comments

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.