0

I have got a nested object. I want to rename the object properties.

  {
     0: {value: "can_view"},
     1: {value: "can_create"}
  }

My output would be:

  {
     user_can: "can_view",
     user_view: "can_create"
  }
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30
sujon
  • 357
  • 3
  • 14

2 Answers2

4

You can do that in three steps:

  • Get the entries using Object.entries()
  • Use map() on it and replace each key with the desired value
  • Convert it back to object using Object.fromEntries()

const obj = {
  0: {value: "can_view"},
  1: {value: "can_create"}
}
const res = Object.fromEntries(Object.entries(obj).map(([k, v]) => [v.value, v.value]));
console.log(res)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
1

Improving Maheer Ali's answer. Here you go:

const obj = {
      0: {value: "can_view"},
      1: {value: "can_create"}
    }
    var res = Object.fromEntries(Object.entries(obj).map(([k, v]) => [v.value.replace("can", "user"), v.value]));
    
    var myResutls = JSON.stringify(res).replace(/"(\w+)"\s*:/g, '$1:');
    console.log(myResutls);
    alert(myResutls)

OUTPUT:

  {
   user_view: "can_view",
   user_create: "can_create"
  }
Ranch Camal
  • 501
  • 1
  • 4
  • 12