I want to reverse an object in JavaScript. For Example:
Input: obj ={'one': 1, 'two': 2, 'three':3 }
output: obj ={'three': 3, 'two': 2, 'one':1 }
Is there any method in javascript or lodash?
I want to reverse an object in JavaScript. For Example:
Input: obj ={'one': 1, 'two': 2, 'three':3 }
output: obj ={'three': 3, 'two': 2, 'one':1 }
Is there any method in javascript or lodash?
Share Improve this question edited Aug 8, 2017 at 7:15 Ataur Rahman Munna 3,9151 gold badge25 silver badges35 bronze badges asked Aug 8, 2017 at 7:07 PranavPinarayiPranavPinarayi 3,2175 gold badges24 silver badges33 bronze badges 4- 12 You can't. Objects' keys aren't supposed to be ordered. Some browser do preserve insertion order but there's no reason to count on it. What are you using this for anyways? – Andrew Li Commented Aug 8, 2017 at 7:09
- What is your use case here? We might be able to suggest something for you. – Samuel Toh Commented Aug 8, 2017 at 7:11
- As Andrew pointed out, the order you talk about does not exist. What you can do and probably mean is the way the object gets serialized (to Json) or printed out. You could overwrite the .toString() function of your object in order to print out its properties in an ordered way, for example. – Rob Commented Aug 8, 2017 at 7:18
-
If your object keys are
1/2/3
and the values areone/two/three
then you can sort it inasc
like thatvar obj ={3:'three', 2:'two', 1:'one' } console.log(Object.keys(obj));
though it's not your requirement. – Ataur Rahman Munna Commented Aug 8, 2017 at 7:22
4 Answers
Reset to default 4here is what you're looking for,
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)
Agree with others, the order of keys in object are not guaranteed. But if you are ok with it and you trust its in order of insertion, you can swap them by this function:
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)
do you need something like this ?
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);
Object.values(errors).reverse()