Home > Enterprise >  Replace single quote ONLY FROM THE KEYS of object Javascript
Replace single quote ONLY FROM THE KEYS of object Javascript

Time:01-19

hope everyone is fine, I have a tricky question, from an RPA app I get this object:

let data = {
      Fecha: '2022-12-14T00:00:00',
      Hora: '1899-12-31T16:14:00',
      'Aten.': 73,
      ' Nro  Ing ': 0,
      Cerrada: 'S',
      '    ': '    ',
      ' Nombre  Atenci¾n ': 'AMBULATORIA',
      'EstadoHC.Electronica': '   -   ',
      Profesional: ' GARCIA  CHAVERRA  MADELEINE ',
      Especialidad: ' MEDICINA  GENERAL ',
      Diagnostico: ' ENFERMEDAD  CARDIACA,  NO  ESPECIFICADA ',
      'Num.Cta': 0
    }

As you can see, the key of the object, some of them are a little weird, what i want to do is replace the single quotes from the keys, to get the [Nombre Atenci¾n] value.

What I try is parser the object in a new object with JSON.parse and replace the spaces in the beginning and the end, like this:

let data2 = JSON.parse(JSON.stringify(data).replace(/"\s |\s "/g,'"'));

Then I try to iterate the second object, to get the specific value of the key mentioned before, after replace spaces and characters, but then I get undefined instead of "AMBULATORIA"

for(let dat in data2){
    dat = dat.replace(/\s\s /g, '').replace("¾", 'o');
    console.log(dat.NombreAtencion)
}

Why I use a for to iterate "one single object" is because I get an array of objects like that one, so I have to use the same treatment to every object.

CodePudding user response:

As you can see, the key of the object, some of them are a little weird, what i want to do is replace the single quotes from the keys

There are no single quotes in the object keys. In an object literal, you can put the name of the property in quotes (single or double). The quotes are just delimiters, not part of the property name. You only have to do that if the property name contains a character that isn't allowed in a property literal (which is true of all of your examples — spaces and . are perfectly valid in property names, but not property name literals).

So there's nothing to do, your object already has property names that don't have those quotes in them. You can tell by looking at the property names:

let data = {
    Fecha: '2022-12-14T00:00:00',
    Hora: '1899-12-31T16:14:00',
    'Aten.': 73,
    ' Nro  Ing ': 0,
    Cerrada: 'S',
    '    ': '    ',
    ' Nombre  Atenci¾n ': 'AMBULATORIA',
    'EstadoHC.Electronica': '   -   ',
    Profesional: ' GARCIA  CHAVERRA  MADELEINE ',
    Especialidad: ' MEDICINA  GENERAL ',
    Diagnostico: ' ENFERMEDAD  CARDIACA,  NO  ESPECIFICADA ',
    'Num.Cta': 0
};

console.log("Property names:");
for (const name of Object.keys(data)) {
    console.log(name);
}

console.log("Value of property Aten.: ", data["Aten."]);
.as-console-wrapper {
    max-height: 100% !important;
}

If you want to rationalize those property names so they're things you can use in property name literals (and so they follow the standard conventions for JavaScript property names), you could have a Map with the original name and the new name you'd like to use, and then create a new object with the new names for the properties:

let data = {
    Fecha: "2022-12-14T00:00:00",
    Hora: "1899-12-31T16:14:00",
    "Aten.": 73,
    " Nro  Ing ": 0,
    Cerrada: "S",
    "    ": "    ",
    " Nombre  Atenci¾n ": "AMBULATORIA",
    "EstadoHC.Electronica": "   -   ",
    Profesional: " GARCIA  CHAVERRA  MADELEINE ",
    Especialidad: " MEDICINA  GENERAL ",
    Diagnostico: " ENFERMEDAD  CARDIACA,  NO  ESPECIFICADA ",
    "Num.Cta": 0,
};

const nameMap = new Map([
    ["Fecha", "fecha"],
    ["Hora", "hora"],
    ["Aten.", "aten"],
    [" Nro  Ing ", "norIng"],
    ["Cerrada", "cerrada"],
    ["    ", "spaces"], // Or whatever
    [" Nombre  Atenci¾n ", "nombreAtencion"],
    ["EstadoHC.Electronica", "estadoHCElectronica"],
    ["Profesional", "profesional"],
    ["Especialidad", "especialidad"],
    ["Diagnostico", "diagnostico"],
    ["Num.Cta", "numCta"],
]);
const updated = Object.fromEntries(
    Object.entries(data).map(([name, value]) => [nameMap.get(name) ?? name, value])
);

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

Or using a simple loop instead of Object.fromEntries, Object.entries, and map:

let data = {
    Fecha: "2022-12-14T00:00:00",
    Hora: "1899-12-31T16:14:00",
    "Aten.": 73,
    " Nro  Ing ": 0,
    Cerrada: "S",
    "    ": "    ",
    " Nombre  Atenci¾n ": "AMBULATORIA",
    "EstadoHC.Electronica": "   -   ",
    Profesional: " GARCIA  CHAVERRA  MADELEINE ",
    Especialidad: " MEDICINA  GENERAL ",
    Diagnostico: " ENFERMEDAD  CARDIACA,  NO  ESPECIFICADA ",
    "Num.Cta": 0,
};

const nameMap = new Map([
    ["Fecha", "fecha"],
    ["Hora", "hora"],
    ["Aten.", "aten"],
    [" Nro  Ing ", "norIng"],
    ["Cerrada", "cerrada"],
    ["    ", "spaces"], // Or whatever
    [" Nombre  Atenci¾n ", "nombreAtencion"],
    ["EstadoHC.Electronica", "estadoHCElectronica"],
    ["Profesional", "profesional"],
    ["Especialidad", "especialidad"],
    ["Diagnostico", "diagnostico"],
    ["Num.Cta", "numCta"],
]);
const updated = {};
for (const name of Object.keys(data)) {
    const newName = nameMap.get(name) ?? name;
    updated[newName] = data[name];
}

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

Or if you want to do it with some rules, here's an example treating . as a space, removing extraneous spaces, and converting to standard camelCase:

let data = {
    Fecha: "2022-12-14T00:00:00",
    Hora: "1899-12-31T16:14:00",
    "Aten.": 73,
    " Nro  Ing ": 0,
    Cerrada: "S",
    "    ": "    ",
    " Nombre  Atenci¾n ": "AMBULATORIA",
    "EstadoHC.Electronica": "   -   ",
    Profesional: " GARCIA  CHAVERRA  MADELEINE ",
    Especialidad: " MEDICINA  GENERAL ",
    Diagnostico: " ENFERMEDAD  CARDIACA,  NO  ESPECIFICADA ",
    "Num.Cta": 0,
};

function convertName(name) {
    // Convert anything that isn't A-Za-z0-9_ to a space,
    // and trim any leading/trailing spaces
    name = name.replace(/[^\w]/g, " ").trim();
    // If blank, bail early
    if (!name) {
        return "__unkown__";
    }
    // Split into words at a series of spaceds
    let words = name.split(/  /);
    // Make the first word all lower-case, and make remaining words lower
    // case except the first letter
    words[0] = words[0].toLowerCase();
    for (let n = 1; n < words.length;   n) {
        words[n] = words[n][0].toUpperCase()   words[0].substring(1).toLowerCase();
    }
    // Join the result
    return words.join("");
}

const updated = Object.fromEntries(
    Object.entries(data).map(([name, value]) => [convertName(name), value])
);

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

Or (again) using a simple loop instead of Object.fromEntries, Object.entries, and map:

let data = {
    Fecha: "2022-12-14T00:00:00",
    Hora: "1899-12-31T16:14:00",
    "Aten.": 73,
    " Nro  Ing ": 0,
    Cerrada: "S",
    "    ": "    ",
    " Nombre  Atenci¾n ": "AMBULATORIA",
    "EstadoHC.Electronica": "   -   ",
    Profesional: " GARCIA  CHAVERRA  MADELEINE ",
    Especialidad: " MEDICINA  GENERAL ",
    Diagnostico: " ENFERMEDAD  CARDIACA,  NO  ESPECIFICADA ",
    "Num.Cta": 0,
};

function convertName(name) {
    // Convert anything that isn't A-Za-z0-9_ to a space,
    // and trim any leading/trailing spaces
    name = name.replace(/[^\w]/g, " ").trim();
    // If blank, bail early
    if (!name) {
        return "__unkown__";
    }
    // Split into words at a series of spaceds
    let words = name.split(/  /);
    // Make the first word all lower-case, and make remaining words lower
    // case except the first letter
    words[0] = words[0].toLowerCase();
    for (let n = 1; n < words.length;   n) {
        words[n] = words[n][0].toUpperCase()   words[0].substring(1).toLowerCase();
    }
    // Join the result
    return words.join("");
}

const updated = {};
for (const name of Object.keys(data)) {
    const newName = convertName(name);
    updated[newName] = data[name];
}
console.log(updated);
.as-console-wrapper {
    max-height: 100% !important;
}

  • Related