Rename all object keys of an array using Javascript

You can rename all object keys of an array with new keys so easy by two ways below:

1 - Use the map method:

const array = [
  { id: "1", name: "Apple" },
  { id: "2", name: "Tomato" },
  { id: "3", name: "Orange" },
  { id: "4", name: "Coconut" },
  { id: "5", name: "Strawberry" },
  { id: "6", name: "Banana" }
];

const newArray = array.map(item => {
  return { itemId: item.id, itemName: item.name };
});

// Result:
// [
//   { itemId: "1", itemName: "Apple" },
//   { itemId: "2", itemName: "Tomato" },
//   { itemId: "3", itemName: "Orange" },
//   { itemId: "4", itemName: "Coconut" },
//   { itemId: "5", itemName: "Strawberry" },
//   { itemId: "6", itemName: "Banana" }
// ];


2 - Create a util function for re-use with more code use Object.keys method:

const changeKeyObjects = (arr, replaceKeys) => {
  return arr.map(item => {
    const newItem = {};
    Object.keys(item).forEach(key => {
      newItem[replaceKeys[key]] = item[[key]];
    });
    return newItem;
  });
};


Use:

const array = [
  { id: "1", name: "Apple" },
  { id: "2", name: "Tomato" },
  { id: "3", name: "Orange" },
  { id: "4", name: "Coconut" },
  { id: "5", name: "Strawberry" },
  { id: "6", name: "Banana" }
];

// enter what key that you want to change by old key in an object
const replaceKeys = { id: "itemId", name: "itemName" };

const newArray = changeKeyObjects(array, replaceKeys);
// Result:
// [
//   { itemId: "1", itemName: "Apple" },
//   { itemId: "2", itemName: "Tomato" },
//   { itemId: "3", itemName: "Orange" },
//   { itemId: "4", itemName: "Coconut" },
//   { itemId: "5", itemName: "Strawberry" },
//   { itemId: "6", itemName: "Banana" }
// ];


javascriptrename object key

© 2019 4codev

Created with love by Sil.