Solved

JavaScript: Add item to BEGINNING of object (NOT ARRAY)

Posted on 2014-01-20
1
536 Views
Last Modified: 2014-01-20
How can I add an item to the beginning of an object?  This adds it to the end:
var obj = {"O":"-","R":"-","L":"-","D":"-"};
obj.W="-";
alert(JSON.stringify(obj));

Open in new window

I was advised to use unshift() however that seems to only work with arrays.  This must stay an object, and the desired order must be maintained.
0
Comment
Question by:hankknight
1 Comment
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 39795873
Test page : http://jsfiddle.net/KpA8v/2/

var obj = {"O":"-","R":"-","L":"-","D":"-"};// YOUR LINE

var bck = obj;
obj = {};

obj.W="-";// YOUR LINE


for(var i in bck) obj[i] = bck[i];

alert(JSON.stringify(obj));// YOUR LINE

Open in new window

0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers. …
Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now