Reputation: 71
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],
}
}
}
Upvotes: 1
Views: 119
Reputation: 31
const obj = {oldKey: 'value'};
obj['newKey'] = obj['oldKey'];
delete obj['oldKey'];
console.log(obj); // 👉️ {newKey: 'value'}
Upvotes: 0
Reputation: 182
const data = [{
'File_12345.ZLM':{
MeterID_12345: {
BASIC_INFO: []
}
}
},{ 'File_678910.ZLM': { MeterID_678910: { BASIC_INFO: [], } } }]
const obj = data.map(item => {
const Meterkeys = Object.keys(item)
const Meterkey = Meterkeys.find(k => k.includes('File'))
if (Meterkey) {
const Filekeys = Object.keys(item[Meterkey])
const Filekey = Filekeys.find(k => k.includes('Meter'))
const res = {
...item,
FileName: {
...item[Meterkey],
MeterId: (item[Meterkey])[Filekey]
}
}
delete res[Meterkey]
delete res.FileName[Filekey]
return res;
} else {
return item
}
})
console.log(obj)
Upvotes: 0
Reputation: 4780
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 }
Upvotes: 2
Reputation: 15711
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};
}));
Upvotes: 1