I got a result like this :
const result = [ 'arg', 'arg2', '[opt1, opt2]' ]
How can I check in this array if a string can be a array ('[opt1, opt2]') and formate it in real array ?
Thank you
EDIT :
I explain all problem :
I want create a script :
yarn start arg1 arg2 "[option1, option2]"
I need a array of options but I can have a lot args without restrictions, when I recover the result :
const res = process.argv.slice(2)
How can I find my array of options ?
You can try the following solution with string manipulation
const result = ['arg', 'arg2', "[option1, option2]"]
const output = result.map(item => {
if (/^\[.+\]$/.test(item)) {
const prepared = item
.replace('[', '["')
.replace(']', '"]')
.replace(/([a-zA-Z0-9]+),+\s+/g, '$1", "')
return JSON.parse(prepared)
}
return item
})
console.log(output)
Explanation:
/^\[.+\]$/ regex - checks whether the element is an array (based on the presence of matching square brackets)
all other replace statements change the string into valid string encoded JSON array.
Since the overall result is a valid string encoded JSON array, just use JSON.parse after that and return it.
Related
I want to validate a pandas formula that is getting inputted to my frontend by the end-user:
This along with a dummy data containing csv is sent to the backend where these formulaes are parsed using eval function in a try-catch block and if the system catches any error a response is returned accordingly.
What I am interested in doing is from an input string that looks something like this:
"csv['Date']+env['filename']+csv['Spend']"
and an array that looks something like this:
const locatedDfs = ['csv','env']
I want to create a dictionary/object that looks something like this:
{
csv: {Date:'',Spend:''},
env: {filename: ''}
}
What the above function does is basically scans the entire string with respect to the locatedDfs array/list and checks if there are any keys for the same and if a key exists, then it initializes that pair with an empty string.
You can use a regular expression that separates the matching results in two groups, the key and the value
const data = "csv['Date']+env['filename']+csv['Spend']+test['123_abc']";
const locatedDfs = ['csv','env'];
// 1. Create a regex that matches: $1['$2']
const regex = /(\w+)\[\'(\w+)\'\]/gm;
// 2. Create an empty object to store the results.
const result = {};
// Start searching the regex in the data
let match = regex.exec(data);
do {
// The match will return an array with 3 values
//
// [0] => The complete match, for example: csv['Date']
// [1] => The first match group (\w+) or $1: csv
// [2] => The second match group ['(\w+)'] or $2: Date
//
// Using array destruction we can store it as variables
const [, key, value] = match;
// Store the matched values into the result.
result[key] = { ...(result[key] || {}), [value]: '' };
} while ((match = regex.exec(data)) !== null) // Continue iterating until there's no more matches.
const expectedResult = locatedDfs.reduce((returnObj, current) => ({ ...returnObj, [current]: result[current] }), {});
console.log(expectedResult);
For example:
str = "A=sample_text1; B=sample_text2; C=sample_text3;";
How can I get the text after "A=", which is "sample_text1" out ? (the length of sample_text1 can be very long, so str.substring won't work here)
Looks like your string has a structure where there are multiple fields where each field is represented as:
[KEY]=[VALUE];
You can use common string and array methods like split and map to extract what you need. In this case looks like you want the value of the first field:
const str = 'A=sample_text1; B=sample_text2; C=sample_text3;';
const result = str.split(';').map(s => s.split('=').pop().trim()).shift();
console.log(result); //=> 'sample_text1'
https://regexr.com is very useful for creating and testing regex.
const match = "A=sample_text1; B=sample_text2; C=sample_text3;".match(/A=([^;]*)/);
let value = match !== null ? match[1] : undefined;
Would allow you to get the value of A in this case
You could use a regular expression to capture every group surrounded by a = and a ;:
const str = "A=sample_text1; B=sample_text2; C=sample_text3;";
const regexp = "=(.*?);";
const values = [...str.matchAll(regexp)];
const aValue = values[0][1];
console.log(aValue);
It might be an overkill, but to easily access to all the keys / values, you could use Object.fromEntries:
let str = "A=sample_text1; B=sample_text2; C=sample_text3;";
let values = Object.fromEntries(
str
// Split all the pairs
.split(";")
// Remove the last empty element
.slice(0,-1)
// map to a [key, value] array to pass to Object.fromEntries
.map(i => i.split("=").map(j => j.trim())));
// get a value using a key
console.log(values["A"]) // sample_text1
// check if a key is present
console.log("C" in values) // true
console.log("D" in values) // false
It looks more longer than it is due the comments and the console logs, it can fit in one line.
Notice that this is assume of course that neither the character = or ; can be part of the key or the value.
I have 2 Javascripts Array
var array1 = ["Mergen Morry","Dash Borad","Mergen Xss"];
var array2 = ["02111356","4458763","02111356"];
I want the output to be like this
Mergen Morry – 02111356 : data uploaded
Dash Borad - 4458763 : data uploaded
Mergen Xss – 02111356 : id already registered
I was thinking using join(), but as I recall this is 2 array, and using concat() are out of question, and maybe was thinking using map() or forEach(), but I still don't get how.
Edit : I'm sorry, the output should be string not array.
You could take an object for keeping seen id and return appropriate comments for mapping strings.
const
names = ["Mergen Morry", "Dash Borad", "Mergen Xss"],
ids = ["02111356", "4458763", "02111356"],
result = names.map(
(seen => (s, i) => `${s} - ${ids[i]} : ${ seen[ids[i]]
? 'id already registered'
: (seen[ids[i]] = true, 'data uploaded') }`)
({})
).join('\n');
console.log(result);
#Nina Scholz answer is pretty good, and here the another way you could have json with all its content instead.
var array1 = ["Mergen Morry","Dash Borad","Mergen Xss"];
var array2 = ["02111356","4458763","02111356"];
var res = array1.map((item,index)=>{
return {name:item,id:array2[index]}
},[]);
// Now that you have an array with Id and namne, you could loop throw each array and display the data
console.log(res)
My array look like this after use this code -:
var array=xmlhttrequest.responseText;
console.log(array);
["{\"result\":{\"isvalid\":true,\"address\":\"3EL5SKSjEzFQDBmXA5JFbsZu48vKnNSdDH\",\"scriptPubKey\":\"a9148aa3d53255b44655f82d163f37ecb68057f2edf487\",\"ismine\":false,\"iswatchonly\":false,\"isscript\":true},\"error\":null,\"id\":\"curltest\"}\n"]
I want value of isvalid , how can i get this .
That's a strange response. It's a stringified array, and that array contains a single item, which is another stringified object. Here's one option:
const responseText = String.raw`["{\"result\":{\"isvalid\":true,\"address\":\"3EL5SKSjEzFQDBmXA5JFbsZu48vKnNSdDH\",\"scriptPubKey\":\"a9148aa3d53255b44655f82d163f37ecb68057f2edf487\",\"ismine\":false,\"iswatchonly\":false,\"isscript\":true},\"error\":null,\"id\":\"curltest\"}\n"]`;
const [ stringItem ] = JSON.parse(responseText);
const itemObj = JSON.parse(stringItem);
const isvalid = itemObj.result.isvalid;
console.log(isvalid);
Note: While testing like this, you have to use String.raw so that the single backslashes are interpreted as literal backslashes and not unnecessary escape characters
The whole thing is an array as you can see it is wrapped inside [ ]. The inner content is a string, so you need to JSON.parse to convert into an object. Here is how you will get it JSON.parse(myData[0]).result.isvalid
var myData = ["{\"result\":{\"isvalid\":true,\"address\":\"3EL5SKSjEzFQDBmXA5JFbsZu48vKnNSdDH\",\"scriptPubKey\":\"a9148aa3d53255b44655f82d163f37ecb68057f2edf487\",\"ismine\":false,\"iswatchonly\":false,\"isscript\":true},\"error\":null,\"id\":\"curltest\"}\n"];
console.log("Is Valid: "+JSON.parse(myData[0]).result.isvalid);
use JSON.parse:
var obj = JSON.parse(array);
but I would try and eliminate all the unnecessary chars before using string.replace:
var json = array.replace("\", "");
I am querying my db in node and have got the result in the form of an object like this - [ [1234] ].
I want to extract this value and convert it into a string and then pass it onto the client side. I have written the other required code but I am not able to get value from this object. Can anyone help me in getting the value and converting it to string?
Since, the result you've got is a two-dimensional array, you can get the value and convert it into a string (using toString() method) in the following way ...
var result = [ [1234] ];
var string;
result.forEach(function(e) {
string = e.toString();
});
console.log(string);
** this solution will also work if you have multiple results, ie. [ [1234], [5678] ]
You have a nested array, meaning that you have an array inside another array:
[ [1234] ]
// ^-^====^-^
To get the first value of the parent array, use the square brackets: [0]. Remember that indexes start at 0!
If you have val = [[1234]], val[0] gets the enclosed array: [1234]. Then, 1234 is a value in that array (the first value), so you use the square brackets again to get it: val[0][0].
To convert to string, you can use + "" which forces the number to become a string, or the toString() method.
var val = [[1234]];
var str = val[0][0] + "";
// or val[0][0].toString();
console.log(str, typeof str);
You can read more about arrays here.
var response = [ [1234] ];
console.log(response[0][0]);
to extract values from a string array or an array we can use .toString()
Ex:
let names = ["peter","joe","harry"];
let fname = names.toString();
output = peter ,joe,harry
or
let name:string[] = this.customerContacts.map(
res => res.firstname
let fname =name.toString();
Using De-structuring Array concept:
const arr = [[1, 2, 3, 4, 5]];
const [[p, q, r, s, t]] = arr;
console.log(p, q, r, s, t);
Output: 1 2 3 4 5