Find key by its index number in an object list and replace with new user input value

Have an object like

{
  A: { lists: 2, name: 'John' },
  B: { lists: 2, name: 'Tom' },
  C: { lists: 1, name: 'Harry' }
}

Here what I want to achieve is select the object key based on its index in the list of object and replace that key with a new input value.

Lets say index id 1 and new key value is T then the key B will be replaced with T and the new object will return as

{
  A: { lists: 2, name: 'John' },
  T: { lists: 2, name: 'Tom' },
  C: { lists: 1, name: 'Harry' }
}

Any help would be great. I have gone through other questions but the answers are not helpful for me.

Answer

You could use Array.prototype.reduce() method. Get key-value pairs array using Object.entries() method. Then traverse the array using reduce and change the required key. At last, return the resultant object.

const change = (array, index, key) => {
  return Object.entries(array).reduce((prev, [x, y], i) => {
    const p = prev;
    if (i === index) p[key] = { ...y };
    else p[x] = { ...y };
    return p;
  }, {});
};
const data = {
  A: { lists: 2, name: 'John' },
  B: { lists: 2, name: 'Tom' },
  C: { lists: 1, name: 'Harry' },
};
const ret = change(data, 1, 'T');
console.log(ret);