Adding values to the start of a JSON associative array using JS

Associate
Joined
15 Feb 2006
Posts
1,872
Location
hell
Hi guys,

I have a bit of a problem here that I'm struggling.

Essentially I'm building a site that refreshes the page using javascript, without changing the URL. I'm adding hash values to the URL during this process so that to the user it looks like a different page and can be shared / bookmarked.

I've created some javascript that uses window.location.hash to get the contents of the hash, which I can then store as a variable and use to serve content relevant to whatever the hash value is.

The problem is, my content is stored in a json array that is dynamically created using PHP/MYSQL from a database. I want to add the hash value and relevant fields to the BEGINNING of this json array.

here's an example of what the json array looks like:

var storenumbers = [
{
name: "carl1",
age: "20"
},
{
name: "dave2",
age: "43"
},
{
name: "pete3",
age: "80"
},
{
name: "sarah4",
age: "25"
},
{
name: "mary5",
age: "28"
}

];

I've created my javascript so that it will delete the hash value from the array if it's included automatically by the PHP.

playlist.splice(myPosition,1);

Now I want to add "myPosition" back into the array, at the beginning...

Does anyone know how to do this?

Thanks
 
Thanks for the reply Phunky,

Yes a lot of people are telling me that! :) Can I call it a json object then?

I'm using splice, instead of delete, as I want the whole index removed, not just the data (from what I hear, this is what splice does).

unshift sounds like it could do the trick, but will it work for what I'm trying to do, e.g. add a name AND an age to the start of the object?

A lot of what I see online only focuses on adding one element...how would I do that?

Cheers
 
Back
Top Bottom