无法交换json键值对。我为这个问题附加了一个JSFiddle。
http://jsfiddle.net/j1acz4dp/4/
console.log(swap({"MYR":"_code","CNY":"_code","JPY":"_code"});
console.log(swap({A : 1, B : 2, C : 3, D : 4}));
function swap(json){
var ret = {};
for(var key in json){
ret[json[key]] = key;
}
return ret;
}
我期望的结果是:
{_code:"MYR",_code:"CNY",_code:"JPY"}
但我得到的结果是:
{ _code: "JPY" }
这是错误的。
最佳答案
我们如何才能做到这一点?[{_code:"MYR"}, {_code:"CNY"}, {_code:"JPY"}]
c = {"MYR":"_code","CNY":"_code","JPY":"_code"}
r = Object.entries(c).map( ([k,v]) => ({[v]:k}) )
console.log(r);