Reputation: 9
I am new to JavaScript programming, and I am having a headache trying to figure it out how to reverse keys of a single JSON object. This is the object that I'm trying to reverse:
{70: "a",
276: "b ",
277: "c ",
688: "d",
841: "e",
842: "f",
843: "g",
1078: "h",
1079: "i"}
I am running this code on localhost. I am analysing the console.logs with google chrome developer tools( F12 ). I can also use Jquery
in this script.
This is what I've tried so far:
//The object is stored in a variable called json
var json =
{70: "a",
276: "b ",
277: "c ",
688: "d",
841: "e",
842: "f",
843: "g",
1078: "h",
1079: "i"};
var entries = Object.entries(json);
entries.reverse();
var newjson = Object.fromEntries(entries);
console.log(newjson);
When I run this code, the output is the same as the old json variable, is inaltered.
And this is the expected console.log()
{ 1079: "i",
1078: "h",
843: "g",
842: "f",
841: "e",
688: "d",
277: "c",
276: "b",
70: "a",
}
Much thanks to anyone who tries to help me.
Upvotes: 1
Views: 1007
Reputation: 1667
As adam-lassek said in this post Javascript associative arrays are unordered. You must write your own function to reverse your array as did yossi-neiman in this post
Upvotes: 0
Reputation: 6842
I hope this helps. I'm not even sure about the performance. Feel free to vote down as long you give me feedback.
Let's say you have the json
var:
const reversedKeys = Object.keys(json).reverse();
const reversedJson = reversedKeys.map(e => ({[e]: json[Number(e)]}) );
Upvotes: 1
Reputation: 6005
Consider that the order of the elements in an object is NOT preserved. In practice, JavaScript object is a dictionary, where, internally, data are not stored in a sequential manner such as in an Array, and values are accessed using a hash function that takes a key as input and - in a simplified sense, gives the "position" of the value inside the structure.
Dictionary is a Data Structure that does NOT preserve ordering (yet, it provides fast data retrieval via indexing), not in JavaScript, or in any other programming language.
I suggest that you use an array for preserving order.
Maybe an array containing different objects could be a solution for you. You can then sort the array based on the key of the object. Here is a "dummy" example:
var arr = [{1: "Test1"}, {2: "Test2"}]
arr.sort((obj1, obj2) => {
return Object.keys(obj2)[0] - Object.keys(obj1)[0];
});
Upvotes: 0