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

I want output like this :

let obj ={ 
 three: 3, 
 two : 2, 
 one : 1 
}
let keys = Object.keys(obj);
obj = keys.reverse();
6
  • 6
    Objects cannot guarantee order - only arrays. Commented Nov 17, 2022 at 19:01
  • there is no guarantee on any order of presentation of keys in a js object, especially when converting JSON to JS object hogs system resources Commented Nov 17, 2022 at 19:10
  • 1
    If order is not important, what's the point of the question? Commented Nov 17, 2022 at 19:14
  • I am constructing a new json object via old object so, to make new json object shuffled everytime , I had need this technique Commented Nov 17, 2022 at 19:46
  • 1
    You confuse. the word JSON refers to textual syntax. It is not a javascript object. there is no JSON in your question. Commented Nov 17, 2022 at 21:06

2 Answers 2

2

Use Object.entries to generate an array of [key,value] pairs, then use Object.fromEntries() to convert it back into an object after reversing.

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

let output = Object.fromEntries(Object.entries(obj).reverse())

console.log(output)

Sign up to request clarification or add additional context in comments.

Comments

1

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

// 👇️ ['3', '2', '1']
const reversedKeys = Object.keys(obj).reverse();

reversedKeys.forEach(key => {
  console.log(key, obj[key]); 
});

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

// 👇️ ['3', '2', '1']
const reversedKeys = Object.keys(obj).reverse();

reversedKeys.forEach(key => {
  console.log(key, obj[key]); 
});

1 Comment

Actually reversedKeys would yield ['one', 'two', 'three']

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.