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
  • 5,385
  • 2
  • 20
  • 27
sujon
  • 339
  • 3
  • 10

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
  • 34,163
  • 5
  • 36
  • 62
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
  • 445
  • 1
  • 4
  • 10