我有一个 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",
"500N\n*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);
关于javascript - 交换 JSON 键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45534263/