Home > Blockchain >  How to rename multidimensional array keys in javascript?
How to rename multidimensional array keys in javascript?

Time:04-25

im trying to rename the keys of this array:

'oldname': [
       {"name": "cat", "category": "animal"}
       ,{"name": "dog", "category": "animal"}
       ,{"name": "pig", "category": "animal"}
           ],
 'oldname1': [
       {"name": "pikachu", "category": "pokemon"}
       ,{"name": "Arbok", "category": "pokemon"}
       ,{"name": "Eevee", "category": "pokemon"}
             ]

i tried with this code:

        const obj = {oldKey: Object.values(result)};

        delete Object.assign(results, {newname: obj.oldKey})['oldname'];

        console.log(result);

but I'm doing it wrong because we dont need to effect the value, it should be something like this:

  'newname': [
       {"name": "cat", "category": "animal"}
       ,{"name": "dog", "category": "animal"}
       ,{"name": "pig", "category": "animal"}
           ],
  'newname1': [
       {"name": "pikachu", "category": "pokemon"}
       ,{"name": "Arbok", "category": "pokemon"}
       ,{"name": "Eevee", "category": "pokemon"}
             ]

is there any better way to do it using javascript?

CodePudding user response:

If you do not want to create a new variable/array you can use a for..of loop and Object.entries() as follows:

const
input = { 'oldname': [ {"name": "cat", "category": "animal"} ,{"name": "dog", "category": "animal"} ,{"name": "pig", "category": "animal"} ], 'oldname1': [ {"name": "pikachu", "category": "pokemon"} ,{"name": "Arbok", "category": "pokemon"} ,{"name": "Eevee", "category": "pokemon"} ] },
mapping = {'oldname':'newname','oldname1':'newname1'};

for(let [key,value] of Object.entries(input)) {
    input[mapping[key]] = value;
    delete input[key];
}

console.log( input );

Otherwise you can do it as follows:

const
input = { 'oldname': [ {"name": "cat", "category": "animal"} ,{"name": "dog", "category": "animal"} ,{"name": "pig", "category": "animal"} ], 'oldname1': [ {"name": "pikachu", "category": "pokemon"} ,{"name": "Arbok", "category": "pokemon"} ,{"name": "Eevee", "category": "pokemon"} ] },
mapping = {'oldname':'newname','oldname1':'newname1','oldname2':'newname2','oldnamen':'newnamen'},

output = Object.fromEntries(
    Object.entries(mapping).map(([oldname,newname]) => [newname, input[oldname]])
    .filter(([,value]) => value)
);

console.log( input );

CodePudding user response:

You can use Object.entries and Object.fromEntries to do that

const replaceKeys = (data, mapping) =>
  Object.fromEntries(
    Object.entries(data).map(([k, v]) => [mapping[k] || k, v])
  )
  
const data1 = {
 oldName1: 1,
 oldName2: 2,
 anotherKey: 3
}

const mapping = {
  oldName1: 'newName1',
  oldName2: 'newName2'
}

console.log(replaceKeys(data1, mapping))

  • Related