![](/img/trans.png)
[英]Javascript convert array of objects to an array with only specific keys with ES6
[英]Javascript: Convert a JSON string into ES6 map or other to preserve the order of keys
ES6(或后续版本),Javascript或TypeScript方法中是否存在本机(内置),可以将JSON字符串转换为ES6映射,或者可以选择要实现的自制解析器? 目的是保留JSON字符串编码对象的键顺序。
注意:为了避免先将JSON字符串转换为ECMA脚本/ JavaScript对象(根据定义,该对象没有键的顺序),我故意不使用“ parse”一词。
例如:
{"b": "bar", "a": "foo" } // <-- This is how the JSON string looks
我需要:
{ b: "bar", a: "foo" } // <-- desired (map version of it)
更新
https://jsbin.com/kiqeneluzi/1/edit?js,控制台
我唯一不同的方法是使用正则表达式获取密钥以维持顺序
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)
原版的
如果我了解您要为选项2达到的目标,这就是我的想法。
https://jsbin.com/pocisocoya/1/edit?js,控制台
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)
基本上获取对象的所有键,然后减少它。 reducer函数将每个键转换为对象的功能
function jsonToMap(jsonStr) {
return new Map(JSON.parse(jsonStr));
}
更多详细信息: http : //2ality.com/2015/08/es6-map-json.html
用于循环
let map = new Map();
let jsonObj = {a:'a',b:'b',c:'c'}
for (let i in jsonObj){
map.set(i,jsonObj[i]);
}
顺便说一句,我看到下面的评论,我认为地图没有排序,因为您使用键来实现地图中的数据,而不是索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.