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

1
  • Comments are not for extended discussion; this conversation has been moved to chat. Commented Sep 8, 2021 at 18:07

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

2 Comments

@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.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.