反转 javascript 中的对象

问题描述 投票:0回答:4

我想在 JavaScript 中反转一个对象。例如:

输入:

obj ={'one': 1, 'two': 2, 'three':3 }

输出:

obj ={'three': 3, 'two': 2, 'one':1 }

javascript或lodash中有什么方法吗?

javascript object lodash
4个回答
2
投票

这就是您要找的,

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
投票

同意其他人的观点,不保证对象中键的顺序。但如果你同意它并且你相信它的插入顺序,你可以通过这个函数交换它们:

reverseObj = (obj) =>{
    return Object.keys(obj).reverse().reduce((a,key,i)=>{
        a[key] = obj[key];
        return a;
    }, {})
};
const result = reverseObj({a: 'aaa', b:'bbb', c: 'ccc'})
console.log(result)


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


0
投票
Object.values(errors).reverse()
© www.soinside.com 2019 - 2024. All rights reserved.