交换JSON密钥和值

时间:2017-08-06 16:42:00

标签: javascript json object

我有一个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>

2 个答案:

答案 0 :(得分:1)

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

注意:您需要在字符串中转义\n

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

使用此代码:

$.ajaxSettings.async = false;
$.getJSON(url, data, function(data){ });
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"
};

function swap(json){
var ret = {};
for(var key in json){
ret[json[key]] = key;
}
return ret;
}

console.log(myObj);
console.log(swap(myObj));