我想在JavaScript中反转一个对象。例如:
输入:obj ={'one': 1, 'two': 2, 'three':3 }
输出:obj ={'three': 3, 'two': 2, 'one':1 }
javascript或lodash中有任何方法吗?
答案 0 :(得分:1)
这是你要找的东西,
function dict_reverse(obj) {
new_obj= {}
rev_obj = Object.keys(obj).reverse();
rev_obj.forEach(function(i) {
new_obj[i] = obj[i];
})
return new_obj;
}
my_dict = {'one': 1, 'two': 2, 'three':3 }
rev = dict_reverse(my_dict)
console.log(rev)
答案 1 :(得分:0)
let obj ={'one': 1, 'two': 2, 'three':3 };
let result = {}, stack = [];
for(property in obj){
stack.push({'property' : property, 'value' : obj[property]})
}
for(let i=stack.length-1;i>=0;i--){
result[stack[i].property] = stack[i].value;
}
console.log(result);