简体   繁体   English

仅从 object 的键替换单引号 Javascript

[英]Replace single quote ONLY FROM THE KEYS of object Javascript

hope everyone is fine, I have a tricky question, from an RPA app I get this object:希望每个人都很好,我有一个棘手的问题,从 RPA 应用程序我得到这个 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.如您所见,object 的密钥,其中一些有点奇怪,我想做的是替换密钥中的单引号,以获得[Nombre Atenci¾n]值。

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:我尝试的是用 JSON.parse 解析新的 object 中的 object 并替换开头和结尾的空格,如下所示:

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"然后我尝试迭代第二个 object,以获取之前提到的键的具体值,在替换空格和字符之后,但是我得到的是未定义而不是“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.为什么我使用 for 来迭代“一个单一的对象”是因为我得到了一个像那个对象的数组,所以我必须对每个 object 使用相同的处理。

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如您所见,object 的密钥,其中一些有点奇怪,我想做的是替换密钥中的单引号

There are no single quotes in the object keys. object 键中没有单引号。 In an object literal, you can put the name of the property in quotes (single or double).在 object 文字中,您可以将属性名称放在引号中(单引号或双引号)。 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.所以没有什么可做的,你的 object已经有属性名称,其中没有这些引号。 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:如果您想使这些属性名称合理化,以便它们是您可以在属性名称文字中使用的东西(因此它们遵循 JavaScript 属性名称的标准约定),您可以使用原始名称和新名称的Map喜欢使用,然后使用属性的新名称创建一个新的 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, }; 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 :或者使用简单的循环代替Object.fromEntriesObject.entriesmap

 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 :或者(再次)使用简单循环代替Object.fromEntriesObject.entriesmap

 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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM