I have some data that I am trying to process with javascript.
DATA:
A. Category one
1. item one
2. item two
B. Category two
3. item three
4. item four
C. Category three
5. item five
6. item six
DESIRED OUTPUT:
[{
"Category one":["item one", "item two"],
"Category two":["item three", "item four"],
"Category three":["item five", "item six"]
}]
Is there a library that will help me with text parsing in javascript?
THIS IS AS FAR AS I GOT:
function parseFormat(str) {
var arr = [];
str.split('\n').forEach(function (line) {
var obj = {};
line.split('.').forEach(function (item) {
if (isNaN(item)) {
// ??
} else {
}
});
return ?;
});
}
Help? Thanks
Here is the complete function. Please have a look at the code below.
Function to parse the string
function parseFormat(strArg) {
var
category,
output = {}, // Output
str = strArg.trim(); // Remove unwanted space before processing
str.split('\n').forEach(function(line) {
var item = line.split('.');
if (item[0].match(/\d/)) { // Match a decimal number
// Remove unwanted space & push
output[category].push(item[1].trim());
} else if (item[0].match(/\D/)) { // Match UPPERCASE alphabet
// Remove unwanted space
category = item[1].trim();
output[category] = []
}
});
return output;
}
Input string
// ES6 Template Strings to define multiline string
var str = `
A. Category one
1. item one
2. item two
B. Category two
3. item three
4. item four
C. Category three
5. item five
6. item six
`;
Function call
// Final output Array
var finalOutput = [];
// Parse input string
var parseStr = parseFormat(str);
finalOutput.push(parseStr);
// Desired JSON output
console.log(JSON.stringify(finalOutput));
You can look at the Browser Console for the desired JSON output.
Hope it helps!
This is a simple way to get the information out of the file format and into some variables. It isn't a complete solution. Though once you get the information into variables you can figure out how to json it.
var category;
var items;
var item = line.split('.'); //Don't use the forEach on the line split.
if (item[0].match(/\d/) ) {
// match a decimal number
items = item[1];
} else if (item[0].match(/\D/) ) {
//match a letter
category = item[1];
}
Related
This is the URL from GeoServer to get feature info
{"type":"FeatureCollection","features":[{"type":"Feature","id":"weather_warning_day_1.fid--418ec0da_178b69d5dfc_-715c","geometry":null,"properties":{"issue_date":"2021-04-09","updated_at":"2021-04-09T09:26:33+05:30","utc_time":0,"state_name":"Odisha","state_id":21,"district_name":"MAYURBHANJ","district_id":232,"api_district_name":"MAYURBHANJ","day_1":"6,9,10","day1_color":3}}],"totalFeatures":"unknown","numberReturned":1,"timeStamp":"2021-04-09T15:38:19.536Z","crs":null}
the data I want to extract is of variable: "day_1":"6,9,10"
which I got from the layer and stored it in the variable as
var warning_day_1 = weather_warning_layer_data.features[0].properties.day_1
so basically the input is "day_1":"6,9,10"
which I have stored in the array as
[{"warning":"6"},{"warning":"9"},{"warning":"10"}]
and corresponding output should be Dust Storm, Heat Wave, Hot Day
Dust Storm, Heat Wave, Hot Day
or if the input was "day_1":"2,5"
then output should have been Heavy Rain, Hailstorm
or if the input was "day_1":"1"
then output should have been No Warning
After reading the data of the string and creating its array, I have to compare it with another array and extract the key values (display) corresponding to the key values (warning) in the 1st array.
var warning_data_split = warning_day_1.split(/[ ,]+/);
var warning_data_from_api_array = new Array;
warning_data_from_api_array.push(warning_data_split);
for (var i = 0; i < warning_data_from_api_array.length; i++) {
var item_in_array_to_compare = warning_data_from_api_array[i];
if(warning_data_from_api_array[item_in_array_to_compare.warning_data_from_api_array])
{warning_data_from_api_array[item_in_array_to_compare.warning_data_from_api_array].push(item_in_array_to_compare);}
else {
warning_data_from_api_array[item_in_array_to_compare.warning_data_from_api_array] = [item_in_array_to_compare];}}
let final_array_to_compare = item_in_array_to_compare
final_array_to_compare = final_array_to_compare.map(x => ({warning: x}));
/// this is the first array ////////////
The values in this array are not static in length, as it keeps on changing like, sometimes the array has value [1] or [1,2], [2,5,8], [4,7,12], etc
so I have to extract the corresponding values of display from the lookup array given below
var warning_code_meaning_list = [
{ warning:"1", display:"No Warning"},
{ warning:"2", display:"Heavy Rain"},
{ warning:"3", display:"Heavy Snow"},
{ warning:"4", display:"Thunderstorm & Lightning, Squall etc"},
{ warning:"5", display:"Hailstorm"},
{ warning:"6", display:"Dust Storm"},
{ warning:"7", display:"Dust Raising Winds"},
{ warning:"8", display:"Strong Surface Winds"},
{ warning:"9", display:"Heat Wave"},
{ warning:"10", display:"Hot Day"},
{ warning:"11", display:"Warm Night"},
{ warning:"12", display:"Cold Wave"},
{ warning:"13", display:"Cold Day"},
{ warning:"14", display:"Ground Frost"},
{ warning:"15", display:"Fog"}
]
The data which I am getting in warning_day_1 (in the very first line of the code) is a string (this couldn’t be saved as float/integer in the database column because sometimes there are more than 1 warning for a specific place, so I have stored this as a text in the database)
Which I’m converting to an array after reading it from the API
Now this string, which I am fetching from API has variable data,
Some time single digit like: 1
Sometime multiple : 1,2,3
And each of the integer present in this array corresponds to the specific text shown in the next array like if the warning is 2 it means the heavy rainfall,
but if the string (later converted to an array, with “warning” as a key) has 2,5 as value, it means: heavy rainfall & Hailstorm
I want that the values which come up in array 1 (the dynamic one) got match with the 2nd array ( a sort of lookup array) and fetch its display value as output.
How to do so?
You could use an object to map your warnings to messages.
Try this:
const data = {"type":"FeatureCollection","features":[{"type":"Feature","id":"weather_warning_day_1.fid--418ec0da_178b69d5dfc_-715c","geometry":null,"properties":{"issue_date":"2021-04-09","updated_at":"2021-04-09T09:26:33+05:30","utc_time":0,"state_name":"Odisha","state_id":21,"district_name":"MAYURBHANJ","district_id":232,"api_district_name":"MAYURBHANJ","day_1":"6,9,10","day1_color":3}}],"totalFeatures":"unknown","numberReturned":1,"timeStamp":"2021-04-09T15:38:19.536Z","crs":null}
var warning_code_meaning_list = {
"1":"No Warning",
"2":"Heavy Rain",
"3":"Heavy Snow",
"4":"Thunderstorm & Lightning, Squall etc",
"5":"Hailstorm",
"6":"Dust Storm",
"7":"Dust Raising Winds",
"8":"Strong Surface Winds",
"9":"Heat Wave",
"10":"Hot Day",
"11":"Warm Night",
"12":"Cold Wave",
"13":"Cold Day",
"14":"Ground Frost",
"15":"Fog",
};
results = data["features"].map(feature => {
return feature.properties.day_1.split(',').map(code => {
return warning_code_meaning_list[code];
});
});
That gives you an array of arrays of the displays:
[ [ 'Dust Storm', 'Heat Wave', 'Hot Day' ] ]
I have an array of objects containing lots of data or objects which I import and display in a webpage.
const arr = [
{
question: "What is molecular formula for water?",
options: ["H2O","CO2","H2O","H2O"]
}
]
So Is it possible to write superscript and subscript in a string? To make the numbers superscipted or subscripted while displaying in a webpage.
Note: I have array of around 1000 objects from which only 100 of them are displayed. Some of them may contain superscript whereas some of them may not. Isn't there any simpler way like using alt codes for super scripts and subscripts so that I can directly put it in string.
You could map your array of options to a formatted version of that option by using .replace() to wrap each number in <sup></sup> tags to make it appear as subscript text like so:
const arr = [
{
question: "What is molecular formula for water?",
options: ["H2O","CO2","H2O","H2O"]
}
]
const formatted = arr[0].options.map(elem => elem.replace(/(\d)/g, `<sub>$1</sub>`));
console.log(formatted);
document.body.innerHTML = formatted;
Regex free approach. Supports hydrated salts (like blue vitorl) and balancing numbers. To add hydrated salts, just add a dot
const arr = [{
question: "What is molecular formula for water?",
options: ["H2O", "CO2", "H2O", "H2O"]
},
{
question: "What is the molecular formula for Copper(II) sulphate?",
options: ["H2O", "(CuSO4).5H2O", "H2O2", "D2O"]
}
]
arr.forEach(obj => { // map the first array
let answer = obj["options"].map((options) => { // map all the answers
let op = options.split('').map((data, i) => { // split all the answer strings
if (!isNaN(data)) { // if the data is a number the add <sub> tags to it
if (options.split('')[i - 1] != "." && i != 0) { // if i = 0 is a number then it is a blancing number. Then don't add <sub> tags to it
// also check if the previous string is a dot. Means that has water of crystillization or any other extension
let str = "<sub>" + data + "</sub>"
return str
}else{
return data
}
} else {
return data // else return the string
}
})
return op.join("") // join the string
})
// logic to add data display it
let question = document.createElement("h1") // question
question.innerHTML = obj["question"] // append question content
document.body.appendChild(question) // append the question element to body
let ul = document.createElement("ul") // create unsorted list
answer.forEach((things) => { // for each of the answers
let ali = document.createElement("li") // create a li
ali.innerHTML = things // add answers to the lu
ul.appendChild(ali) // append the li to the ul
})
document.body.appendChild(ul) // append the ul to the body
})
We are just splitting your answers and checking if the data is a number. If it is then we add <sub> tags to it.
To display them, we create elements dynamically and in a loop, we add compounds to a li and then append that to a ul
Make sure to follow the basic chem rules while formatting compounds
Generic example for replacing digits in all values with unicode subscript digits :
var json = JSON.stringify( [ { question: "What is molecular formula for water?", options: ["H2O","CO2","H2O","H2O"] } ] )
var arr = JSON.parse(json, (k, v) => v.trim ? v.replace(/\d/, m => '₀₁₂₃₄₅₆₇₈₉'[m]) : v)
console.log(arr)
document.body.textContent = arr[0].options
I have some data that I need to convert to an array, but I can't get the regex quite working. I just need a one dimensional array, don't need the numbers, just the values - but the items with line breaks is messing it up.
Regex: ([0-9]\-\ )(.*)([\s]*)
Test: https://regex101.com/r/F9UIG8/1
Data:
1- TEST DATA.
1- TEST DATA THAT GOES ONTO
TWO LINES.
2- MORE TESTS.
1- ADDITIONAL MULTILINE
DATA WITH
SEVERAL LINES
3- MORE TEST 3
4- MORE TEST 4
1- MORE SUB ITEMS
2- SUB ITEM 2
3- SUB ITEM MULTILINE
SECOND LINE
4- MORE
2- EVEN MORE TWO LINE
SECOND LINE
1- DATA
2- DATA
3- DATA
4- DATA TWO LINE
2ND LINE.
3- LAST BIT OF 2 LINE DATA
WITH SECOND LINE
Try this regular expression with the split() method:
let text = `1- TEST DATA.
1- TEST DATA THAT GOES ONTO
TWO LINES.
2- MORE TESTS.
1- ADDITIONAL MULTILINE
DATA WITH
SEVERAL LINES
3- MORE TEST 3
4- MORE TEST 4
1- MORE SUB ITEMS
2- SUB ITEM 2
3- SUB ITEM MULTILINE
SECOND LINE
4- MORE
2- EVEN MORE TWO LINE
SECOND LINE
1- DATA
2- DATA
3- DATA
4- DATA TWO LINE
2ND LINE.
3- LAST BIT OF 2 LINE DATA`;
text.split(/\s*\d\-/igm);
It will return an array with the texts (including line breaks), removing the numbers and hypens.
Thanks for your assistance, I've built this into a google apps script using a variation of the answer from #ncardeli.
function JSONIFYRANGE(range, asJSON){
var array = new Array();
for (var i = 0; i < range.length; i++) {
array.push({name: range[i][0], items: JSONIFY(range[i][1], asJSON)});
}
return JSON.stringify(array);
}
function JSONIFY(input, asJSON) {
if(input.indexOf("[ ]") >= 0 || input.indexOf("[ ]") >= 0 || input.indexOf("[ ]") >= 0){
return JSONIFY2(input, asJSON);
} else {
return JSONIFY1(input, asJSON);
}
}
function JSONIFY1(input, asJSON) {
var json = input.split(/\s*\d\-/igm); // answer from #ncardeli
var newArray = new Array();
for (var i = 0; i < json.length; i++) {
if (json[i] != "") {
newArray.push(json[i].replace("SOME COMMON TEXT I DONT WANT IN THE ITEMS", "").trim());
}
}
return asJSON ? newArray : JSON.stringify(newArray);
}
function JSONIFY2(input, asJSON) {
var json = input.split(/\s*\[\s*\]/igm);
var newArray = new Array();
for (var i = 0; i < json.length; i++) {
if (json[i] != "") {
newArray.push(json[i].trim());
}
}
return asJSON ? newArray : JSON.stringify(newArray);
}
Using it like: =JSONIFYRANGE('Items'!B2:C40, true) where B column holds the list name and C column holds the string to be split into items, outputs a JSON string with the following signature:
{[
{
name: "List 1 Name",
items: [
"TEST DATA THAT GOES INTO TWO LINES",
"MORE TESTS.",
...
]
},
{
name: "List 2 name",
items: [
"SOME ITEM",
"SOME OTHER ITEM",
...
]
},
...
]}
I am attempting to extract JSON values (from structure called jsonWithListOfStatesAndCounters) if it matches with an element in my inputted array (inputedJurisdictionArray). My inputed array contains sting values that include singular or multiple state names (i.e. var inputedJurisdictionArray = ["Iowa", "California, Indiana, Delaware", "Florida"]). The singular State values in this array are handled normally at the end, but the multiple state values is where it gets tricky. I am using split() in order to turn them into another array so they can get processed one by one. Anytime one of the states from this inputed array matches with a "state" value in jsonWithListOfStatesAndCounters, I am extracting it into another JSON structure and pushing it at the end of every block into my initial variable myJurisdictionJSON. The problem I am having is that once these forEach loops are completed, I am still left with my original values in myJurisdictionJSON, instead of the val and counter that should be extracted. The jsonWithListOfStatesAndCounters definitely contains the values that should match with the elements of my inputedJurisdictionArray, but the information is not being pushed into myJurisdictionJSON. What am I doing wrong? Any tips/pointers will be helpful.
var myJurisdictionJSON = [{
jurisdiction_val: 'jurisdiction_val',
jurisdiction_counter: 'jurisdiction_counter'
}];
inputedJurisdictionArray.forEach(function each(item) {
if (Array.isArray(item)) {
item.forEach(each);
} else {
var jurisdictionInput = item;
jsonWithListOfStatesAndCounters.forEach(function each(item) {
if (Array.isArray(item)) {
item.forEach(each);
} else {
if (jurisdictionInput.includes(",") === true){//Checking if more than one jurisdiction in string
var jurisdictionArr = jurisdictionInput.split(", ");
var jurisdictionCounter = item.jurisdictionCounter;
var jurisdictionState = item.jurisdictionState;
jurisdictionArr.forEach(function(element) {
if (myJurisdictionJSON.jurisdiction_counter == 'jurisdiction_counter'){ // If nothing is pushed into our predefined JSON object
if (jurisdictionState.toLowerCase() == trim(element.toLowerCase())) {
var jurisdictionJSON_inner = {
jurisdiction_val: element,
jurisdiction_counter: jurisdictionCounter
};
myJurisdictionJSON.push(jurisdictionJSON_inner);
return;
}
}else if (myJurisdictionJSON.jurisdiction_counter != 'jurisdiction_counter'){ // if an item has been pushed into myJurisdictionJSON, append the next items
var jurisdictionCounter = item.jurisdictionCounter;
var jurisdictionState = item.jurisdictionState;
if (jurisdictionState.toLowerCase() == trim(jurisdictionInput.toLowerCase())) {
jurisdictionJSON_inner.jurisdiction_val = jurisdictionJSON_inner.jurisdiction_val + ", " + jurisdictionInput;
jurisdictionJSON_inner.jurisdiction_counter = jurisdictionJSON_inner.jurisdiction_counter + ", " + jurisdictionCounter;
myJurisdictionJSON.push(jurisdictionJSON_inner);
return;
}
}
});
}
else{// if only one jurisdiction state in jurisdictionInput string
var jurisdictionCounter = item.jurisdictionCounter;
var jurisdictionState = item.jurisdictionState;
if (jurisdictionState.toLowerCase() == trim(jurisdictionInput.toLowerCase())) {
var jurisdictionJSON_inner = {
jurisdiction_val: jurisdictionInput,
jurisdiction_counter: jurisdictionCounter
};
myJurisdictionJSON.push(jurisdictionJSON_inner);
return;
}
}
}
});
I'm not totally sure the output is what you want but it's close.
// input data as per your example
let inputedJurisdictionArray = [
'Iowa',
'California, Indiana, Delaware',
'Florida'
];
// I had to make this part up. It's missing from the example
let jsonWithListOfStatesAndCounters = [{
jurisdictionCounter: 2,
jurisdictionState: 'Florida'
},
{
jurisdictionCounter: 4,
jurisdictionState: 'Indiana'
},
{
jurisdictionCounter: 3,
jurisdictionState: 'Texas'
}
];
// first, fix up inputedJurisdictionArray
// reduce() loops over each array element
// in this case we're actually returning a LARGER
// array instead of a reduced on but this method works
// There's a few things going on here. We split, the current element
// on the ','. Taht gives us an array. We call map() on it.
// this also loops over each value of the array and returns an
// array of the same length. So on each loop, trim() the whitespace
// Then make the accumulator concatenate the current array.
// Fat arrow ( => ) functions return the results when it's one statement.
inputedJurisdictionArray = inputedJurisdictionArray.reduce(
(acc, curr) => acc.concat(curr.split(',').map(el => el.trim())), []
);
// now we can filter() jsonWithListOfStatesAndCounters. Loop through
// each element. If its jurisdictionState property happens to be in
// the inputedJurisdictionArray array, then add it to the
// myJurisdictionJSON array.
let myJurisdictionJSON = jsonWithListOfStatesAndCounters.filter(el =>
inputedJurisdictionArray['includes'](el.jurisdictionState)
);
console.log(myJurisdictionJSON);
I am creating a dictionary app in React, I have loaded in the JSON dictionary which looks like this:
{
"DIPLOBLASTIC": "Characterizing the ovum when it has two primary germinallayers.",
"DEFIGURE": "To delineate. [Obs.]These two stones as they are here defigured. Weever.",
"LOMBARD": "Of or pertaining to Lombardy, or the inhabitants of Lombardy.",
"BAHAISM": "The religious tenets or practices of the Bahais.",
"FUMERELL": "See Femerell."
}
The user enters a word in the input field and the value is then passed into the following function to search for a matching key in the JSON. Matching words are then pushed into an array of results with their respective value.
handleSearch: function(term) {
var term = term;
var results = [];
for (var key in Dictionary) {
if (Dictionary.hasOwnProperty(key)) {
if (term == Dictionary[key]) {
results.push(Dictionary[key])
}
}
}
console.log(results)
},
However I am struggling to find a successful way of looping through it to get results. the console is logging an empty array.
Can anyone please suggest where I am going wrong?
You can have better matching by adding a compare function (in example below it is the compareTerm function). What I did there is comparing if the term STARTS with the dictionary key, if you want it to be any part of the string you can change it from === 0 to > -1.
// compare function which needs to be added somewhere
function compareTerm(term, compareTo) {
var shortenedCompareTo = compareTo
.split('')
.slice(0, term.length)
.join('');
return term.indexOf(shortenedCompareTo.toLowerCase()) === 0;
}
// only changed the compare function
handleSearch: function(term) {
var results = [];
for (var key in Dictionary) {
if (Dictionary.hasOwnProperty(key)) {
if (compareTerm(term, Dictionary[key])) {
results.push(Dictionary[key])
}
}
}
console.log(results);
},