1

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"};
5
  • The first 'array' looks like a json object. Commented Sep 23, 2014 at 12:02
  • 4
    @reporter What are you talking about? It looks an a JS array literal. Commented Sep 23, 2014 at 12:03
  • yes your right, I mixed the syntax a little bit with an array Commented Sep 23, 2014 at 12:04
  • @reporter JSON uses a subset of Javascript literal notation. Commented Sep 23, 2014 at 12:05
  • @Barmar as I have already wrote, I mixed up the syntax with the array. Commented Sep 23, 2014 at 12:09

2 Answers 2

4

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.