简体   繁体   中英

How to rename multidimensional array keys in javascript?

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM