0

I'm new to Javascript and I'm having trouble rename a series of elements inside objects, how do I change all the names? I understand that I can change it using table[0].id = "Code", but it's not practical if my Array got too big.

{
"Table": [
    {
        "id": "1104567",
        "year": "2015",
        "Name": "Richard"
    },
    {
        "id": "1104568",
        "year": "2016",
        "Name": "Rener"
    }
]
}

I'm trying to get something like this:

{
"Table": [
    {
        "Code": "1104567",
        "year": "2015",
        "Name": "Richard"
    },
    {
        "Code": "1104568",
        "year": "2016",
        "Name": "Rener"
    }
]
}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Guilherme
  • 3
  • 1

3 Answers3

0

For example:

const data = {
  "Table": [
    {
      "id": "1104567",
      "year": "2015",
      "Name": "Richard"
    },
    {
      "id": "1104568",
      "year": "2016",
      "Name": "Rener"
    }
  ]
};

for (const el of data.Table) {
  el.Code = el.id;
  delete el.id; 
}

console.log(data);

For multiple renamings:

const data = {
  "Table": [
    {
      "id": "1104567",
      "year": "2015",
      "Name": "Richard"
    },
    {
      "id": "1104568",
      "year": "2016",
      "Name": "Rener"
    }
  ]
};

const newKeyMapping = {
  id: 'Code',
  year: 'Year',  
};

for (const el of data.Table) {
  for (const [oldKey, newKey] of Object.entries(newKeyMapping)) {
    el[newKey] = el[oldKey];
    delete el[oldKey]; 
  }
}

console.log(data);
MikeM
  • 13,156
  • 2
  • 34
  • 47
0

This can be done with the map method.

let result = data.Table.map(element => {
  return {
    'Code': element.id,
    'year': element.year,
    'Name': element.Name
  }
})
akopyl
  • 298
  • 2
  • 12
0

This solution (alternative to using delete) utilizes entries and this answer is based on this old question

let data = {
  "Table": [
      {
          "id": "1104567",
          "year": "2015",
          "Name": "Richard"
      },
      {
          "id": "1104568",
          "year": "2016",
          "Name": "Rener"
      }
    ]
}

let keysToUpdate = {
  "id": "Code"
}

const updatedData = data.Table.map(obj =>
  Object.fromEntries(Object.entries(obj).map(([k, v]) => [keysToUpdate[k] || k, v]))
);

console.log(updatedData);
Tony M
  • 741
  • 4
  • 16