Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

JavaScript: Add item to BEGINNING of object

Posted on 2014-01-20
3
Medium Priority
?
400 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 83

Accepted Solution

by:
leakim971 earned 1600 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 400 total points
ID: 39795840
0
 
LVL 83

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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
This article discusses how to create an extensible mechanism for linked drop downs.
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…
Suggested Courses

810 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