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.
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;
}
I'm trying to take a JSON Array and display the full output, but nicely formatted. (see commented out section) Unfortunately the JSON array returns back with OBJECT then its output. So I stringify to fix the [Object, Object] error I was getting. But now everything is on one line. How do iterate through the array and put them on new lines?
Second issue I'm having is, I can't do 3 of the same functions as you notice in the uncommented section. I'd like to take each result and add a new line in between them.
function setTitleStatus(context, settings) {
$SD.api.setTitle(context, "Updating...");
getResults(result => resultCallback(result, context));
}
function resultCallback(result, context) {
if (!result.hasOwnProperty("Object")) {
$SD.api.setTitle(context, JSON.stringify(result));
console.log(JSON.stringify(result, '%c%s'));
return;
}
// This is where I'd like all 3 objects to be split on new lines.
// $SD.api.setTitle(context, result.Platform.replace(new RegExp(' ', 'g'), '\n') +
// "\n" + result.Platform + " ")
// $SD.api.setTitle(context, result.PU.replace(new RegExp(' ', 'g'), '\n') +
// "\n" + result.PU + " ")
// $SD.api.setTitle(context, result.EA.replace(new RegExp(' ', 'g'), '\n') +
// "\n" + result.EA + " ")
}
function getResults(updateTitleFn) {
let endPoint = "https://status.robertsspaceindustries.com/static/content/api/v0/systems.en.json";
$.getJSON(endPoint)
.done(function (response) {
updateTitleFn({
"Platform": response[0].status,
"PU": response[1].status,
"EA": response[2].status,
});
console.log("Platform", response[0].status)
console.log("PU", response[1].status)
console.log("EA", response[2].status)
})
}
Update
If I uncomment the sections this is what it shows. Its hard to tell but whats happening is, its taking replacing setTitle three times, and taking the last line. $SD.api.setTitle(context, result.EA.replace(new RegExp(' ', 'g'), '\n') +
"\n" + result.EA + " ")
Via Screenshot
To get nicely formatted output from JSON.stringify, supply the optional arguments:
JSON.stringify(obj, null, 2)
let arr = ["Pineapple", "Lemon", "Apple", "Orange", "Peach"];
document.getElementById('result').innerHTML =
'Stringify default: ' + JSON.stringify(arr) + '\n\n' +
'Stringify formatted: ' + JSON.stringify(arr, null, 2);
<pre id="result"></pre>
This question already has answers here:
How to access a numeric property?
(3 answers)
Closed 4 years ago.
var s = '{"1" : "Sammy", "2" : "Shark", "3" : "Ocean"}';
var obj = JSON.parse(s);
document.getElementById("user").innerHTML =
"Name: " + obj.1 + " " + obj.2 + "<br>" +
"Location: " + obj.3;
Error from console:
Uncaught SyntaxError: Unexpected number
Use bracket notation to access numeric keys of an object:
const obj = { "1": "Sammy" };
console.log(obj["1"]);
Same goes for using some other character, for example -:
const obj = { "test-123": "works only with bracket notation" };
console.log(obj["test-123"]);
As gurvinder372 suggests, identifier cannot be numeric, you tried to access object's property with a number, which is wrong.
Correct Code
var s = JSON.parse('{"1" : "Sammy", "2" : "Shark", "3" : "Ocean"}');
document.getElementById("user").innerHTML =
"Name: " + s["1"] + " " + s["2"] + "<br>" +
"Location: " + s["3"];
you cannot have numbers after . (dot operator)
you should try using [].
var s = '{"1" : "Sammy", "2" : "Shark", "3" : "Ocean"}';
var obj = JSON.parse(s);
document.getElementById("user").innerHTML =
"Name: " + obj[1] + " " + obj[2] + "<br>" +
"Location: " + obj[3];
how can I concat more rationally first item of array to first of second array and so on? Basically automate console.log here is the code:
$("button#search").on("click", function(){
var inputVal = $("input#text").val();
$.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&search=" + inputVal +"&limit=5&namespace=0&format=json&callback=?", function(json) {
var itemName = $.each(json[1], function(i, val){
})
var itemDescription = $.each(json[2], function(i, val){
})
var itemLink = $.each(json[3], function(i, val){
})
console.log(itemName[0] + " " + itemDescription[0] + " " + itemLink[0]);
console.log(itemName[1] + " " + itemDescription[1] + " " + itemLink[1]);
console.log(itemName[2] + " " + itemDescription[2] + " " + itemLink[2]);
console.log(itemName[3] + " " + itemDescription[3] + " " + itemLink[3]);
console.log(itemName[4] + " " + itemDescription[4] + " " + itemLink[4]);
})//EOF getJSON
});//EOF button click
I believe this is what you are looking for:
for (var i = 0; i < itemName.length; i++) {
console.log(itemName[i] + " " + itemDescription[i] + " " + itemLink[i]);
}
If arrays have the same length, you could use map
var result = $.map(json[1], function(i, val){
var row = val + " " + json[2][i] + " " + json[3][i];
console.log(row);
return row;
}
Also you can use that result later, e.g.
console.log(result[0]);
Using es6 you can do the following:
(in your getJson callback):
function (json) {
const [value, optionsJ, descriptionsJ, linksJ] = json;
let whatIwant = [];
// choose one to loop through since you know they will all be the same length:
optionsJ.forEach(function (option, index) {
whatIwant.push({option: option, description: descriptionJ[index], link: linksJ[index]});
});
// use whatIwant here**
}
Your new whatIwant array will then contain objects for each set.
I have some of this Code:
function writeIslamicDate(adjustment) {
var wdNames = new Array("Ahad","Ithnin","Thulatha","Arbaa","Khams","Jumuah","Sabt");
var iMonthNames = new Array("Muharram","Safar","Rabi'ul Awwal","Rabi'ul Akhir",
"Jumadal Ula","Jumadal Akhira","Rajab","Sha'ban",
"Ramadan","Shawwal","Dhul Qa'ada","Dhul Hijja");
var iDate = kuwaiticalendar(adjustment);
var outputIslamicDate = wdNames[iDate[4]] + ", " + (iDate[5]-1) + " " + iMonthNames[iDate[6]] + " " + iDate[7] + " AH";
return outputIslamicDate;
}
document.write(writeIslamicDate());
Output : Ithnin, 23 Ramadan 1435 AH
?
I want to replace 23 with bengali number ২,৩ ///// or two, three
I watch and try a lot of but couldn't success.. Is there are any to solve this ?
Thanks.
I do like
var someString = (iDate[5]-1) + " " + iMonthNames[iDate[6]] + " " + iDate[7] + " হিজরী";
var outputIslamicDate = somestring.replace(/1/g, "১").replace(/4/g, "৪");
return outputIslamicDate;
but it's not work...
Use regex and the global flag:
str.replace(/word/g, 'word2');