Solved

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

Posted on 2014-01-20
1
649 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

[Webinar] How Hackers Steal Your Credentials

Do You Know How Hackers Steal Your Credentials? Join us and Skyport Systems to learn how hackers steal your credentials and why Active Directory must be secure to stop them. Thursday, July 13, 2017 10:00 A.M. PDT

Question has a verified solution.

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

In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
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

634 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