Joe
Joe

Reputation: 277

JSON Object javascript, how to get value not key

I have an JSON object in javascript

"urls": {"url": "http://www.google.co.uk"}

I want to be able to get the actual URL google.co.uk, not the text 'url'.

I also have a variable called date.

I want to create a New object that holds the url value as the key and set the value to the date '20/10/2013' for example.

"newObject": {"http://www.google.co.uk": "20/10/2013"}

Im sure this is possible however I am not so good with json objects and i welcome any help.

Upvotes: 2

Views: 1990

Answers (2)

cardeol
cardeol

Reputation: 2238

IMHO, you should create a readable array like this

var myArray = [
  { url: "http://www.google.co.uk", date: "20/10/2013"},
  { url: "http://www.google.com", date: "20/10/2014" }
]

then you can parse all elements using a for loop for each object in the array.

var myObject;
var url, date;
for(var k = 0; k < myArray.length; k++)
    myObject = myArray[k];
    url = myObject.url;
    date = myObject.date;
}

If you need speed you can use a Memoization Pattern or create hashes to get O(1) queries.

Upvotes: 5

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

To get the URL, you just have yo do :

var myURL = urls.url;

Then to get the date :

var myDate = newObject[myURL];

Upvotes: 2

Related Questions