How to pass dictionary inside template literal in JS - javascript

How do I pass the whole dictionary inside the template literal?
Here is my code:
var pvtInPlan = treatmentPlan.pavementIDs;
var pcrAfterPlan = treatmentPlan.pavementCondition;
var yearlyPlan = {};
pvtInPlan.forEach((key, i) => yearlyPlan[key] = pcrAfterPlan[i]); // I want to pass this yearlyPlan
var arcadeExpression = `
var plan = ${yearlyPlan};
var pvtID = 100;
return plan[pvtID]`; // I want to be able to return such statement.
Whenever I use 'var plan = ${yearlyPlan};' line, it throws me error. It works when I use 'var plan = ${yearlyPlan[100]};' directly. But I need to pass index to this dictionary from inside of template literal.
I would be glad if someone could help me with this.
Thanks!

You can just do a simple JSON.stringify if u want to dump the entire content, for example:
const yearlyPlan = JSON.stringify({ key1: 'content', key2: 'content2' })
const arcadeExpression = `
var plan = ${yearlyPlan};
var pvtID = 100;
return plan[pvtID]`; // I want to be able to return such statement.
console.log(arcadeExpression)
>>>
"var plan = {"key1":"content","key2":"content2"};
var pvtID = 100;
return plan[pvtID]"
If you want a more customized version, then u would need to access each key-value pair to format the message.

Related

Get payload from String

I have this String:
['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
I want to get the keys 'TEST1-560' which is always fist and "car" value.
Do you know how I can implement this?
This is a very, very scuffed code, but it should work for your purpose if you have a string and you want to go through it. This can definitely be shortened and optimized, but assuming you have the same structure it will be fine.:
// Your data
var z = `['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']`;
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1,dividedVar[ind].split(":")[1].split("}")[0].length-1);
console.log(car)
}
}
console.log(testName);
output:
BLUE
TEST1-560
In a real application, you don't need to log the results, you can simply use the variables testName,car. You can also put this in a function if you want to handle many data, e.g.:
function parseData(z) {
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1, dividedVar[ind].split(":")[1].split("}")[0].length - 1);
}
}
return [testName, car]
}
This will return the variables values in an array you can use
const arr = ['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
const testValue = arr[0];
const carValue = JSON.parse(arr[1]).data[0].car;
console.log(testValue);
console.log('-----------');
console.log(carValue);
If your structure is always the same, your data can be extracted like above.

Oracle Apex changing a String of a object

So I want to get the Object which is essentialy a string. The issue is I cant transfer it into the string format since the resulting string is just anything but the thing I want. Bringing the object into a json doesnt bring a proper string either so my only way of achieving that is the concat method.
I have a Popup-Love which returns the string as follows foo, foo1 ,foo2 while I need it as
'foo1','foo2',...,'foo999' .
My method manages to do that for the first element while all the other elements remove the apostrophe resulting in something like 'foo,foo1,foo2'. How do i fix that?
var i = 0;
if(i == 0){
var t ="'";
var t = t.concat(apex.item("P29_STANDORT").getValue());
var t = t.concat("'");
apex.item("P29_TEST").setValue(t);
i = i +1;
} else {
var t = t.concat("'");
var t = t.concat(apex.item("P29_STANDORT").getValue());
var t = t.concat("'");
apex.item("P29_TEST").setValue(t);
}
You can "overwrite" the native toString() function of the Object and replace it with a function that does what you want. Something like below
function MyObj(){
this.creationTime = new Date().toLocaleString();
}
MyObj.prototype.toString = function something(){
return 'I was created on ' + this.creationTime;
}
var myObj = new MyObj();
console.log('String version of my custom object: ' + myObj);

require() not working with variable - react native

I meet a weird problem. If I set a variable direclty with a value like this "const myString = 'someWord';" that work but if I take the value from a variable like this "const myString = someVariable;", that doesn't work, and if I set the value on a conditional block that doesn't work too.
So, work:
var jsonName = 'tramwayen';
const pathex = require('../assets/JSON/' + jsonName);
var json = JSON.parse(JSON.stringify(pathex));
doesn't work:
var jsonName = variable;
const pathex = require('../assets/JSON/' + jsonName);
var json = JSON.parse(JSON.stringify(pathex));
doesn't work:
var jsonName = '';
if (condition) {
jsonName = 'tramwayen';
}
const pathex = require('../assets/JSON/' + jsonName);
var json = JSON.parse(JSON.stringify(pathex));
I really don't understand.
I have this error :
"Invalid call at line 41: require('../assets/JSON/' + jsonName2)"
Most JS bundlers cannot handle dynamic require imports. You might want to load all of the files, and put them in an object:
let data = {
tramwayen: require('../assets/JSON/tramwayen.json'),
something: require('../assets/JSON/something.json'),
// and so on
};
And use the data object to retrieve the data you need.
From what I read while doing some research, it seems impossible to made a require dynamically. In react native require should be static.
But there are some solutions to avoid this issue.
Here is mine, I put all data of my differents Json on one single json, and I dynamically choice wich part of the data I want to get.
I can also, put all the static require on an object, and choose dynamicaly wich require I want to get.
solution 1:
const id = window.currentPI;
const json = require('../assets/JSON/mainData.json');
const nbreOfPix = json[`${id}`].preData.numberOfPictures;
solution 2:
const IMAGES = {
tramwayen: require('../assets/CtrlPI/PHOTO_articles/008_02_Img.png'),
tramwayen2: require('../assets/CtrlPI/PHOTO_articles/HC002_04_Img.png')
};
getImage = (name) => {
return IMAGES[name];
};

Split Javascript String

I've got a javascript string called cookie and it looks like that:
__utma=43024181.320516738.1346827407.1349695412.1349761990.10; __utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=43024181.19.10.1349761990; __utmc=43024181; language=en
It could have more ;xxxxxx; but always the entries will be surrounded by ;.
Now i want to split my var into a array and search for the entry "language=xy", this entry should be saved in "newCookie".
Could anyone help me please i'm completly stucked at splitting the var into a array and search for the entry.
Thanks for helping and sharing
var cookie = '__utma=43024181.320516738.1346827407.1349695412.1349761990.10; __utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=43024181.19.10.1349761990; __utmc=43024181; language=en;';
var cookie_array = cookie.split(';'); // Create an Array of all cookie values.
// cookie_array[0] = '__utma=43024181.320516738.1346827407.1349695412.1349761990.10'
// cookie_array[1] = '__utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)'
// cookie_array[2] = '__utmb=43024181.19.10.1349761990'
// cookie_array[3] = '__utmc=43024181'
// cookie_array[4] = 'language=en'
var size = cookie_array.length; // Get Array size to prevent doing lookups in a loop.
for (var i = 0; i < size; i++) {
var keyval = cookie_array[i].split('='); // Split into a key value array
// What we're trying to find now.
// keyval[0] = 'language'
// keyval[1] = 'en'
if (keyval[0] == 'language') { //keyval[0] is left of the '='
//write new cookie value here
console.log('Language is set to ' + keyval[1]); // keyval[1] is right side of '='
}
}
Hope this helps ya out.
For more info on the split() method look at split() Mozilla Developer Network (MDN) documentation
Use a simple regexp for this:
var getLanguage = function(cookie){
var re = new RegExp(/language=([a-zA-Z]+);/);
var m = re.exec(cookie);
return m?m[1]:null;
};
var lang = getLanguage('__utma=43024181.320516738.1346827407.1349695412.1349761990.10; __utmz=43024181.1346827407.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=43024181.19.10.1349761990; __utmc=43024181; language=en;');
// lang = "en"

Assigning variables to objects in JavaScript

I am using the following method to basically create a JSON string.
var saveData = {};
saveData.a = 2;
saveData.c = 1;
However the .a and .c don't cut it for what I need to do, I need to replace these with strings. So something like..
var name = 'wibble';
saveData.name = 2;
This would get accessed with
saveData.wibble
Does anyone know how this could be achieved?
var name = "wibble";
saveData[name] = 2;
alert(saveData.wibble);
Note that, in JavaScript, the following notations are equivalent:
obj.key
obj["key"]
Use the map accessor:
var name = 'wibble'
saveData[name] = 2
You can access Javascript objects using a dictionary notation:
var name = 'wibble';
saveData[name] = 2;
saveData.wibble is now 2.

Categories