Home > Back-end >  How to replace the keys "names" in javascript
How to replace the keys "names" in javascript

Time:09-07

Below is the object

{
  'File_12345.ZLM': {    
    MeterID_12345: {     
      BASIC_INFO: [Object]

    }
  }
}
{
  'File_678910.ZLM': {
    MeterID_678910: {
      BASIC_INFO: [Object],
    }
  }
}

===============================================================================================
I want File_12345.ZLM and File_678910.ZLM replaced with key name as "FileName" and MeterID_12345 and MeterID_678910 replaced with "MeterId"

So Expected Output would be as below

{
  'FileName': {    
    MeterId: {     
      BASIC_INFO: [Object]

    }
  }
}
{
  'FileName': {
    MeterId: {
      BASIC_INFO: [Object],
    }
  }
}

CodePudding user response:

As @efkah pointed out, the RegEx solution here:

const files = [{'File_12345.ZLM':{MeterID_12345:{BASIC_INFO:[]}}},{'File_678910.ZLM':{MeterID_678910:{BASIC_INFO:[]}}}];

const renamed = JSON.stringify(files)
  .replaceAll(/File_\d \.ZLM/g, 'FileName')
  .replaceAll(/MeterID_\d /g, 'MeterId');
  
const result = JSON.parse(renamed);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }

CodePudding user response:

The idea is to grab the keys of the objects, since there is only one. With that we get to know the key we want to replace. Do it for both keys and voilà!

I've added a second way to do it, to flatten the objects a bit to make them easier to use, and to also not loose the filename and meterid info.

const files = [{
  'File_12345.ZLM': {    
    MeterID_12345: {     
      BASIC_INFO: []

    }
  }
},
{
  'File_678910.ZLM': {
    MeterID_678910: {
      BASIC_INFO: [],
    }
  }
}];

console.log(files.map(f=>{
  const filename = Object.keys(f)[0];
  f.FileName = f[filename]; delete f[filename];
  const MeterId = Object.keys(f.FileName)[0];
  f.FileName.MeterId = f.FileName[MeterId]; delete f.FileName[MeterId];
  return f;
}));

const files2 = [{
  'File_12345.ZLM': {    
    MeterID_12345: {     
      BASIC_INFO: []

    }
  }
},
{
  'File_678910.ZLM': {
    MeterID_678910: {
      BASIC_INFO: [],
    }
  }
}];
console.log(files2.map(f=>{
  const filename = Object.keys(f)[0];
  const MeterId = Object.keys(f[filename])[0];
  return {FileName:filename,MeterId,BASIC_INFO:f[filename][MeterId].BASIC_INFO};
}));

CodePudding user response:

const obj = {oldKey: 'value'};

obj['newKey'] = obj['oldKey']; delete obj['oldKey'];

console.log(obj); //

  • Related