Solved

JavaScript: Add item to BEGINNING of object

Posted on 2014-01-20
3
364 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={"b":2,"c":3,"d":4};
obj.a=1;
alert(JSON.stringify(obj));

Open in new window

0
Comment
Question by:hankknight
  • 2
3 Comments
 
LVL 82

Accepted Solution

by:
leakim971 earned 400 total points
ID: 39795839
Test page : http://jsfiddle.net/KpA8v/

var obj = {"b":2,"c":3,"d":4};
var bck = obj;
obj = {};
obj.a=1;
for(var i in bck) obj[i] = bck[i];
alert(JSON.stringify(obj));

Open in new window


But if you really need to maintain order use an array : http://jsfiddle.net/KpA8v/1/
var obj = [{"b":2},{"c":3},{"d":4}];
var o = {a:1};
obj.unshift(o);
alert(JSON.stringify(obj));

Open in new window

0
 
LVL 14

Assisted Solution

by:brendanmeyer
brendanmeyer earned 100 total points
ID: 39795840
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39795848
You accepted a bad answer.
unshift is for array not for object.
Additionaly brendanmeyer answer don't follow the rules (bind links) :
http://support.experts-exchange.com/customer/portal/articles/1162518

You should ask a moderator o reopen the question and close it differently or wait for brendanmeyer to give more details about its answer.
0

Featured Post

Highfive Gives IT Their Time Back

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

In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
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…

707 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

13 Experts available now in Live!

Get 1:1 Help Now