Javascript: Convert a JSON string into ES6 map or other to preserve the order of keys

Viewed 773

Is there a native (built in) in ES6 (or subsequent versions), Javascript or in TypeScript method to convert a JSON string to ES6 map OR a self-made parser to be implemented is the option? The goal is to preserve the order of the keys of the JSON string-encoded object.

Note: I deliberately don't use the word "parse" to avoid converting a JSON string first to ECMA script / JavaScript object which by definition has no order of its keys.

For example:

{"b": "bar", "a": "foo" }        // <-- This is how the JSON string looks

I need:

{ b: "bar", a: "foo" }           // <-- desired (map version of it)
3 Answers

UPDATE

https://jsbin.com/kiqeneluzi/1/edit?js,console

The only thing that I do differently is to get the keys with regex to maintain the order

let j = "{\"b\": \"bar\", \"a\": \"foo\", \"1\": \"value\"}"
let js = JSON.parse(j)

// Get the keys and maintain the order
let myRegex = /\"([^"]+)":/g;
let keys = []
while ((m = myRegex.exec(j)) !== null) {
    keys.push(m[1])
}

// Transform each key to an object
let res = keys.reduce(function (acc, curr) {
     acc.push({
         [curr]: js[curr]
    });
    return acc
}, []);


console.log(res)

ORIGINAL

If I understand what you're trying to achieve for option 2. Here's what I came up with.

https://jsbin.com/pocisocoya/1/edit?js,console

let j = "{\"b\": \"bar\", \"a\": \"foo\"}"

let js = JSON.parse(j)

let res = Object.keys(js).reduce(function (acc, curr) {
    acc.push({
      [curr]: js[curr]
    });
    return acc
}, []);


console.log(res)

Basically get all the keys of the object, and then reduce it. What the reducer function convert each keys to an object

use for in loop

let map = new Map();
let jsonObj = {a:'a',b:'b',c:'c'}

for (let i in jsonObj){
map.set(i,jsonObj[i]);
}

btw, i saw the comment below and i think map is not ordered because you use key to achieve data in map, not the index.

Related