0

So I have an object like this:

var obj = { foo: function() { ... }, bar: function() { ... }, baz: 10 };

I want to convert it to this using vanilla ECMAScript 3 Javascript:

[ 
    { name: "foo", value: function() { ... } }, 
    { name: "bar", value: function() { ... } }, 
    { name: "baz", value: 10 }
]

How can I do this?

Note: It has to work on IE8.

3
  • just b\\putting a box i.e var arrayOfObjects = [obj] should do the work. Sorry if not relevant. Commented Jul 27, 2015 at 17:58
  • @kcube You can't do that - it would make an Array of length 1 with the first item as your whole starting object; i.e. if you tried arrayOfObjects[1]; // undefined which is not desired behaviour Commented Jul 27, 2015 at 18:05
  • oops i know that. Just got clear with op's question. In that case, for..in should do. Commented Jul 27, 2015 at 18:12

2 Answers 2

3

A simple for..in loop will do the trick, it's been around since ECMAScript 1.

function o2a(o) {
    var arr = [],
        k;
    for (k in o) {
        arr.push({'name': k, 'value': o[k]});
    }
    return arr;
}

// Now can do

var obj = { foo: function() { /* ... */ }, bar: function() { /* ... */ }, baz: 10 };
o2a(obj);
// [
//    {name:"foo", value: function.. },
//    {name:"bar", value: function.. },
//    {name:"baz", value: 10}
// ]
Sign up to request clarification or add additional context in comments.

3 Comments

Does for..in work in IE8? Can it also be done with a classical for(var i = 0; i < whatever; i++) loop?
for..in works in IE 8. using a 'classical' loop would not work (unless all of your keys were numbers, which clearly they are not)
Another option you have is that you can always re-implement much of ES5 in browsers that don't support it by using a shim or polyfill. I don't see any other way but using for..in to get the keys of an Object below ES5 though
1

For future readers who don't need IE 8 support:

use map with Obect.keys():

myArr = Object.keys(obj).map(function(key) { return {name: key, value: obj[key]} } );

3 Comments

No, I did not see that requirement. Did you just add that in?
No, I just added the IE8 clarification. The ECMAScript 3 requirement was there from the start.
sorry about that. Go with @Paul S. answer

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.