-3

I have object like this :

let data = { name : "Me" , age : "20" }

I want to change object to be like this :

data = {  age : "20" , name : "Me" }
KPTH
  • 91
  • 1
  • 2
  • 12
  • 1
    Possible duplicate of [Sort JavaScript object by key](https://stackoverflow.com/questions/5467129/sort-javascript-object-by-key) – Sebastian Simon Aug 17 '18 at 03:29
  • Possible duplicate of [Changing the order of the Object keys....](https://stackoverflow.com/questions/6959817/changing-the-order-of-the-object-keys) – Blue Aug 17 '18 at 03:35
  • I just noticed that my answer answers the title (sort of) and not the actual question, but I'll leave it, in case the title and question were mis-worded. I have a feeling this will be closed anyways. – ctt Aug 17 '18 at 03:42
  • Why do you want to do this? Object key order shouldn't matter--the idea with objects is to access properties like `.name` and `.age` separately rather than iterate them. The normal ordered data structure is an array. Technically, the spec nowadays guarantees order, but just because you can doesn't mean you should. Even granting you want to do this, it's unclear whether a sort of all keys or a swap of two is requested, and there's no attempt here. – ggorlen Aug 21 '23 at 23:02

1 Answers1

-2

That's a super strange thing to want to do but:

function reverse(data) {
  return Object.entries(data).reduce((reverse, entry) => {
    reverse[entry[1]] = entry[0];
    return reverse;
  }, {})
}

...will swap the keys and values directly within the provided object.

data = { name : "Me" , age : "20" }
reverse(data)
// {20: "age", Me: "name"}
ctt
  • 1,405
  • 8
  • 18