-1
let object1 = { "hello" : [5, 12, 8, 130, 44], "hello1" : [7, 12, 8, 130, 44]};

const oldKey = "hello";
const newKey = "hello4;
const index = Object.keys(object1).findIndex(e => e === oldKey);
Object.keys(object1)[index] = newKey;

console.log(object1);

The key is not changing here for some reason.

dummy
  • 3
  • 3

1 Answers1

0

Begin by setting new key value to old key

then delete the old key

const object1 = { "hello" : [5, 12, 8, 130, 44], "hello1" : [7, 12, 8, 130, 44]};

const oldKey = "hello";
const newKey = "hello4";
object1[newKey]=object1[oldKey];
delete object1[oldKey];

console.log(object1);

edit: now that you changed from const object1 to let object1 there is another way!!

let object1 = { "hello" : [5, 12, 8, 130, 44], "hello1" : [7, 12, 8, 130, 44]};

const oldKey = "hello";
const newKey = "hello4";
object1 = Object.fromEntries(Object.entries(object1).map(([k, v]) => [k === oldKey ? newKey : k, v]))
console.log(object1);
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87