-2

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" }
  • 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) – Goodbye StackExchange 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

1 Answers1

-1

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,337
  • 7
  • 18