2017-08-06 146 views
1

我有一個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", 
       "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

過得好MyObj中?如果myObj已經創建,那麼數據丟失 – marvel308

+0

我有一個文件,其中包含這種格式的所有JSON:https://pastebin.com/Ppv7in9t – William

+0

對不起,但這不是有效的JSON。密鑰在JSON中必須是唯一的。 – vasekhlav

回答

1

如果您可以將您的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);

+2

感謝您使用此解決方案。這適用於我的情況。我將它標記爲正確的答案,因爲數據已經是一個刪除非唯一鍵的對象,所以它不能用javascript解決。 – William

0

使用此代碼:

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));
<!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>

+1

這會在聲明myObj變量時刪除非唯一鍵。 – William