Skip to content Skip to sidebar Skip to footer

Javascript: Convert A Json String Into Es6 Map Or Other To Preserve The Order Of Keys

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

Solution 1:

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 orderlet myRegex = /\"([^"]+)":/g;
let keys = []
while ((m = myRegex.exec(j)) !== null) {
    keys.push(m[1])
}

// Transform each key to an objectlet 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

Solution 2:

functionjsonToMap(jsonStr) {
    returnnewMap(JSON.parse(jsonStr));
}

More details : http://2ality.com/2015/08/es6-map-json.html

Solution 3:

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.

Post a Comment for "Javascript: Convert A Json String Into Es6 Map Or Other To Preserve The Order Of Keys"