0

I have a massive object (around 10k lines) so for the sake of the question I would make an example object with three identical keys

let itemList = [{
A: { 
name: `hello1`,
},
A: { 
name: `hello2`,
},
A: { 
name: `hello3`,
},
}];

Now in this array I am attempting to assign an integral value of each key ( by renaming them so the object turns out to be something like this:

let itemList = [{
A0: { 
name: `hello1`,
},
A1: { 
name: `hello2`,
},
A2: { 
name: `hello3`,
},
}];

Referring to the answer here I used the following logic:

let newObject = {};
let i = 0;
for(let key in itemList){
    renameObjectkey(itemList, key, key + i)
    i++
}

  console.log(newObject)

  function renameObjectkey(object, oldName, newName){
        const updatedObject = {}
        for( let key in object) {
            if (key === oldName) {
                newObject[newName] = object[key]
            } else {
                newObject[key] = object[key]
            }
        }
      
        object = updatedObject
      }

Although it simply changes one of the values and returns me the following:

{A0: { name: `hello`}}

I am looking to achieve my goal, please suggest the most efficient way to do so since its a mega object :P

EDIT I was told to have an array instead, please assist me in a case it was an array, thanks

James Z
  • 12,209
  • 10
  • 24
  • 44
Zero
  • 2,164
  • 1
  • 9
  • 28
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/236911/discussion-on-question-by-zero-renaming-object-keys-in-an-array-with-identical). – Machavity Sep 08 '21 at 18:07

1 Answers1

3

It's possible to convert an array of objects to an object containing numbered keys.
reduce is what you need:

const data = [{
  name: `3rd age amulet`,
  aliases: [`3a ammy`]
}, {
  name: `3rd age axe`,
  aliases: [`3a axe`]
}]

const result = data.reduce((obj, current, index) => {
  obj[`A${index}`] = current;
  return obj;
}, {});

console.log(result);

Or, if your data already contains those A keys:

const data = [{
  A: {
    name: `3rd age amulet`,
    aliases: [`3a ammy`]
  }
}, {
  A: {
    name: `3rd age axe`,
    aliases: [`3a axe`]
  }
}]

const result = data.reduce((obj, current, index) => {
  obj[`A${index}`] = current.A;
  return obj;
}, {});

console.log(result);
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • @Zero, sometimes a bit of discussion is needed to clarify things. Kudos on Cerbrus for the answer, and I'm really happy we could help you out. – Andy Sep 08 '21 at 12:00
  • @Zero: Yea, it's very important that you structure the data like in one of the two examples. Maybe try it with only 2-3 items, first. – Cerbrus Sep 08 '21 at 12:55