yesman
yesman

Reputation: 7838

How do you convert an array of JavaScript objects to a single object?

I have this array:

var objectArray = [{url:"www.google.com", id: "google"}, 
{url:"www.apple.com", id: "apple"}, 
{url:"www.facebook.com", id: "facebook"}];

Is it possible to convert to a JavaScript object that is formed like this:

var newObject = {"google": "www.google.com", 
                 "apple": "www.apple.com",
                 "facebook": "www.facebook.com"};

Upvotes: 1

Views: 57

Answers (2)

Nik Kashi
Nik Kashi

Reputation: 4606

var m={};
objectArray.forEach(function (i){m[i.id]=i.url})

Upvotes: 0

Scimonster
Scimonster

Reputation: 33409

You can manually loop over the array and convert it.

var obj = {};
for (var i = 0; i < objectArray.length; i++) {
   obj[objectArray[i].id] = objectArray[i].url;
}

Upvotes: 4

Related Questions