Search code examples
javascriptarraysobjectkey

JavaScript - How to change object keys in an array of object?


I have an array of object :

let data = [
  { "date" : "17/03/2022", "count" : 2, "[email protected]" : 2 },
  {
    "date" : "17/05/2022",
    "count" : 2,
    "[email protected]" : 1,
    "[email protected]" : 1
  },
  { "date" : "17/07/2022", "count" : 7, "[email protected]" : 7 },
];

I would like to remove "@" in the object key instead of the email address.

This is the expected output :

// Expected output:
data = [
  { "date" : "17/03/2022", "count" : 2, "james" : 2 },
  {
    "date" : "17/05/2022",
    "count" : 2,
    "admin" : 1,
    "secretary" : 1
  },
  { "date" : "17/07/2022", "count" : 7, "staff" : 7 },
];

Notes:

I have tried, but yet not successful :

for (let i = 0; i < data.length; i++) {
  let keys = Object.keys(data[i]);
  console.log(`key-${i+1} :`, keys); // [ 'date', 'count', '[email protected]', '[email protected]' ]
  
  let emails = keys.filter(index => index.includes("@"));
  console.log(`email-${i+1} :`, emails); // [ '[email protected]', '[email protected]' ]
  
  let nameList = [];
  for (let i = 0; i < emails.length; i++) {
    let name = emails[i].split("@")[0];
    nameList.push(name);
  }
  console.log(`name-${i+1} :`, nameList); // [ 'admin', 'secretary' ]
}

Thanks in advance.


Solution

  • You could create a function which splits the keys of the object keys at @ and creates a new object using Object.fromEntries().

    Here's a snippet:

    const data = [{date:"17/03/2022",count:2,"[email protected]":2},{date:"17/05/2022",count:2,"[email protected]":1,"[email protected]":1},{date:"17/07/2022",count:7,"[email protected]":7}];
    
    const converter = o => Object.fromEntries(
      Object.entries(o).map(([k, v]) => [k.split("@")[0], v])
    )
    
    console.log(
      data.map(converter)
    )

    If Object.fromEntries() is not supported, you could use a simple loop through the array and then each object to create new objects like this:

    const output = []
    
    for (const o of data) {
      const updated = {}
      
      for (const key in o) {
        updated[key.split("@")[0]] = o[key]
      }
      
      output.push(updated)
    }