Search code examples
javascriptarraysobjectkey

How to replace all occurrences of an object key in an array? (JavaScript)


So I have an array, containing objects like this:

var items_array = {
 value: 5555,
 shipping: 444,
 transaction_id: 12345678,
  items: [
  {
  id: "1234",
  title: "testitem1",
  unitPrice: 12,
  quantity: 1
  },
  {
  id: "4321",
  title: "testitem2",
  unitPrice: 21,
  quantity: 2
 }]};

Now I want to replace the "id" with "item_id", "unitPrice" with "price" and the title with "item_name" in each object in the array. Sadly, I cannot convert the array into a string, so the .replace method doesn't work here and as far as I know, the .map method only allows me to replace the properties, not the keys themselves. Also, this array can have one or multiple items inside it, so the solution has to work wheter I have 1 item or 50. Also, I can't use "=>" as this is an old javascript enviroment below 1.7 with no support for "modern" solutions like this.

Do you guys have any idea how to do this? I am fairly new to Javascript sadly and my Google skills turned out to be insufficent in this matter. If you need further explaination, please just ask and I will answer to the best of my abilities.


Solution

  • You can take a look on Array.map. Here I use items for example.

    Old browser

    var items = [{
      id: "1234",
      title: "testitem1",
      unitPrice: 12,
      quantity: 1
    }, {
      id: "4321",
      title: "testitem2",
      unitPrice: 21,
      quantity: 2
    }];
    
    var newItems = items.map(function (item) {
      item.item_id = item.id;
      delete item.id;
      item.price = item.unitPrice;
      delete item.unitPrice;
      item.item_name = item.title;
      delete item.title;
      return item;
    });
    
    console.log(newItems);
    

    Modern way

    let items = [
       {
        id: "1234",
        title: "testitem1",
        unitPrice: 12,
        quantity: 1
       },
       {
        id: "4321",
        title: "testitem2",
        unitPrice: 21,
        quantity: 2
       }
    ]
    
    const newItems = items.map((item) => {
      item.item_id = item.id
      delete item.id
    
      item.price = item.unitPrice
      delete item.unitPrice
    
      item.item_name = item.title
      delete item.title
    
      return item
    })
    
    console.log(newItems)