交换 JSON 键和值



我有一个JSON对象,我正在尝试将键与其值交换。这些值都是唯一的,但键不是。由于它们不是唯一的,因此在创建对象时,将删除非唯一键。

无论如何我可以在创建对象之前反转键和值吗?我试图用下划线来做到这一点,但这个库只允许你反转对象。

<!DOCTYPE html>
<html>
<body>
<script src="http://underscorejs.org/underscore-min.js"></script>
<script>
var myObj = {
"503": "07:25",
"507": "06:00",
"500x": "06:50",
"500x": "07:20",
"500": "07:35",
"503": "07:50",
"507": "07:40",
"500x": "07:55",
"500": "08:30",
"500x": "08:00",
"500": "10:45",
"507": "09:05",
"500": "10:45",
"507": "09:05",
"500": "13:45",
"500": "16:45",
"500": "20:00",
"500": "22:00",
"500Nn*Thur/Fri Only": "23:00"
},
myObj = _.invert(myObj),
keys = Object.keys(myObj),
values = Object.values(myObj),
i, len = values.length;
console.log("Total len = " + len) 
values.sort();
console.log(myObj);
for (i = 0; i < len; i++) {
k = keys[i];
v = values[i];
console.log(k + ': ' + v);
}
</script>
</body>
</html>

如果您可以将 obj 转换为字符串,那么使用正则表达式,您可以在""之间获取单词,然后使用 for 循环将它们组合在一起。

注意:您需要对字符串中的n进行转义。

const myObj = '{"503": "07:25","507": "06:00","500x": "06:50","500x": "07:20","500": "07:35","503": "07:50","507": "07:40","500x": "07:55","500": "08:30","500x": "08:00","500": "10:45","507": "09:05","500": "10:45","507": "09:05","500": "13:45","500": "16:45","500": "20:00","500": "22:00", "500N\n*Thur/Fri Only" : "23:00"}';

var result = myObj.match(/"(.*?)"/gm).reduce((res,word)=>{
res.push(word.replace(/"/g,''));
return res;
},[]);
var swapped = {};
for(let i = 0 ; i < result.length - 1; i += 2){
swapped[result[i + 1]] =result[i]
}
console.log(swapped);

使用以下代码:

var myObj = {
"503": "07:25",
"507": "06:00",
"500x": "06:50",
"500x": "07:20",
"500": "07:35",
"503": "07:50",
"507": "07:40",
"500x": "07:55",
"500": "08:30",
"500x": "08:00",
"500": "10:45",
"507": "09:05",
"500": "10:45",
"507": "09:05",
"500": "13:45",
"500": "16:45",
"500": "20:00",
"500": "22:00",
"500Nn*Thur/Fri Only": "23:00"
};
function swap(json){
var ret = {};
for(var key in json){
ret[json[key]] = key;
}
return ret;
}
console.log(myObj);
console.log(swap(myObj));
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://underscorejs.org/underscore-min.js"></script>
</body>
</html>

最新更新