Query syntax for JSON lookup data with var ( not condition ) [duplicate] - javascript

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 6 years ago.
I'm trying to filter some JSON data, but I would like the lookup to be based on selection of a drop down. However, I just can't get the syntax correct when trying to do this. Currently the following works in my code, great:
var as = $(json).filter(function (i, n) {
return (n.FIELD1 === "Yes"
});
However, what I would like to do is replace the FIELD1 value with a var from the drop down. Something like this following, which is not working:
var dropdownResult = "FIELD1";
var as = $(json).filter(function(i, n) {
return (n.dropdownResult === "Yes"
});
I'm trying to get the var to become the field name after the n. but it's not working.
Thanks for your time. Sorry if this has been answered many times before and is obvious to you.

To use a variable value as the key of an object you should use bracket notation, like this:
var dropdownResult = "FIELD1";
var as = $(json).filter(function(i, n) {
return n[dropdownResult] === "Yes";
});
I removed the extraneous ( you left in your code - I presume this was just a typo as it would have created a syntax error and stopped your code from working at all.
Also note that it's much better practice to use a boolean value over a string 'Yes'/'No'

Related

JavaScript RegEx: How do I utilise named capture groups? [duplicate]

This question already has answers here:
Javascript: Named Capture Groups
(2 answers)
Named capturing groups in JavaScript regex?
(10 answers)
Closed last month.
I am currently working at a Plugin for RPG Maker MZ and for that, i learned how to use RegEx for analyzing the Content of a Notetag. While my first try with them was actually pretty good, i assume it didn't used the full potential of RegEx and because i need to expand the my RegEx anyway so the user has more options, i wanted to try out named capture groups for better readability and easier access for me as a developer.
Unfortionatly, i wasnt able to find out how to get the "group" object of the objects i got from the Iterator from matchAll(). So my question would be how to analyse the content of a named capture group in javascript.
Important: as far as i saw, the other questions didnt answer the question why i wasnt be able to find the right group object. also, most of the answers are with the exec function instead of the matchAll function.
The for this part relevant Code is:
const regex1new = /(?<ItemCategory>Item|Armor|Weapon)\s*:\s*(?<ID>\d+)\s*(?<Weight>w:(?<WeightFactor>\d+))?/gm;
let foundTagEntrysList = Array.from(this.enemy().meta.HellsCommonDropList.matchAll(regex1new), entry => entry[0]); //If you wanna reproduce this, just replace this.enemy().meta.HellsCommonDropList with a string
newTagsAnalyser();
function newTagsAnalyser() {
foundTagEntrysList.forEach(matchedElement => {
let Item;
let Weight;
let ID = matchedElement.groups.ID;
switch (matchedElement.groups.ItemCategory) {
case "Item":
Item = $dataItems[ID];
break;
case "Weapon":
Item = $dataWeapon[ID];
break;
case "Armor":
Item = $dataArmor[ID];
break;
default:
break;
}
if (typeof matchedElement.groups.Weight !== 'undefined'){
Weight = matchedElement.groups.WeightFactor;
}
commonItemDataMap.set(Item, Weight);
});
}
What did i expected?
That the matechedElement.group.xxx returnes the content of the group that is named xxx.
What was the result?
rmmz_managers.js:2032 TypeError: Cannot read property 'ID' of undefined

String replace in JavaScript (like Query Binding) [duplicate]

This question already has answers here:
How can I do string interpolation in JavaScript?
(21 answers)
Closed 3 years ago.
Thank you for answering my question, I think this is not interpolation so I change the title and before you mark this as duplicate as string interpolation in JavaScript please read the question carefully, because I already read the other interpolation question for JavaScript but not one of them is have the same way that I want for my code (I tell the reason on the question), and I don't want to use Plugin.
Hi all, first I want you to know about my purpose in this code, you can tell this main reason is to build Query Binding for Express with MySQL, but I will use this code for other reason also.
I want to know about string interpolation in Javascript / Typescript that will work like Query Binding in code in Code Igniter source
// Code 1
let person = 'ujang'
let age = 23
console.log("Hello, %s. You're age is %d years old.", person, age)
// Hello, ujang. You're age is 23 years old.
// The function is similiar to this code
// $sql = "insert into tbl_user (name, age, groupname) values (?, ?, ?)";
// $this->db->query($sql,array('codeigniter, 35, 'Group 1'));
As can you see in above code I use console.log and it's working as I want it, but because the console.log is void and not returning any value I can't use it in real condition.
// Code 2
const str = 'helow, %s. and you want %d piece of cake.?'
const name = 'ujang'
const want = 13
const myFunction = (value, ...optionalParams) => {
// The function I want is similiar with Query Binding in Code Igniter
// And it can handle dynamicly params
// This only sample
value = value.replace('%s', optionalParams[0])
value = value.replace('%d', optionalParams[1])
return value
}
myFunction(str, name, want)
// helow, ujang. and you want 13 piece of cake.?
In Code 2 I'll try making a function, that working as expected, but only for static params.
// Code 3
const names = 'ujang'
const arg1 = 'good'
const argN = 'better'
const dontWantFunction = (value, arg1, argN) => {
return `helow, ${value}, this function is ${arg1} but any ${argN} solution.?`
}
dontWantFunction(names, arg1, argN)
// helow, ujang, this function is good but any better solution.?
In Code 3 is function that I don't really want, because is hard to manage and have more hardcode text inside the function.
Is anyone know how to fill myFunction in Code 2.?
or anyone working on similar code.?
or know some documentation / article that will lead me to this solution.?
I'am waiting for your response that will help me a lot,
Thank you for attention.
You can try something like this, where we take out the values from optionalParams in sequential manner and replace on matching value
const str = 'helow, {{value}}. and you want {{value}} piece of cake.?'
const name = 'ujang'
const want = 13
const myFunction = (value, ...optionalParams) => {
return value.replace(/\{\{value\}\}/g, (m) => optionalParams.shift() || m)
}
console.log(myFunction(str, name, want))

Create array names dynamically based on string values in Array Javascript [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 7 years ago.
var sub=["Maths","Chemistry","Physics"];
for(var i=0;i<sub.length;i++)
{
var sub[i]=[]; // this line has error
}
I want to create and get result as below:
Maths[],Chemistry[],Physics[]
If it is not possible to get in this way is there any alternate in Javascript to achieve the same
var sub=["Maths","Chemistry","Physics"];
var result = {};
for(var i=0;i<sub.length;i++)
{
result[sub[i]] = [];
}
I also recommend you read this article which has a good explanation on how to use objects as associative arrays.
Hopefully this example helps in addition to the above responses. You can past this code in a browser console and play around with it.
var dict = {Math:[], Physics:[], Chemistry:[]};
dict["Math"] = [0, 1, 2];
dict["Chemistry"] = ["organics", "biochemistry"];
dict["Physics"] = ["kinematics", "vectors"];
/*retrieve code by typing following one by one*/
dict["Math"]
dict["Chemistry"]
dict["Physics"]

Getting the first item in an [word, word] [duplicate]

This question already has answers here:
How to get the first element of an array?
(35 answers)
Closed 8 years ago.
I am trying to get the first word out of the variable var solution = [cow, pig]
I have tried everything from strings to arrays and I can't get it. Please help.
As per the comments
solution[0]
Will return the first item in the array.
solution[1]
would be the second, or undefined if the array was:
var solution = [cow]
Is solution an array, or is it in that form? (var solution = [cow, pig]) You also need to add quotes around those values, unless those values are defined variables.
You need to change the variable to look like this:
var solution = ['cow', 'pig']
If so, just get the value at subscript 0.
var result = solution[0];
console.log(result);
If you mean an string like
solution = "cow pig".
Do
solution = solution.split(' ')[0];
console.log(solution); //Will return cow

variable as object key in javascript [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Use javascript variable in object name
I am using CKeditor as a rich text editor. I have dynamically generated textareas with a unique ID that need replacing with text editors. That is working fine, but I then need to call getData(); on the textarea to get the data for an AJAX call. This is easy enough:
var editor_data = CKEDITOR.instances.editor1.getData();
The problem is I need editor1 to be dynamic, depending on the value of an attribute on a button. I record the textarea's identifier in a sibling button's name attribute:
var INSTANCE_NAME = $(this).attr('name');
Logging that out I get the correct editor ID back. (Note only using CAPS to highlight where it needs to be used in the next code block.)
I now need to use that INSTANCE_NAME as a variable like so:
var editor_data = CKEDITOR.instances.INSTANCE_NAME.getData();
I imagine my entire code needs to look something like this:
var INSTANCE_NAME = $(this).attr('name');
var editor_data = CKEDITOR.instances.INSTANCE_NAME.getData();
But I just get an error that CKEDITOR.instances.INSTANCE_NAME is undefined (which isn't surprising really)
Thanks
There are two ways to access properties in an object:
object.property
object['property']
Because the second option takes the property name as a string, you can build it dynamically — in this case, using the string INSTANCE_NAME:
var INSTANCE_NAME = $(this).attr('name');
var editor_data = CKEDITOR.instances[INSTANCE_NAME].getData();
// \_____________/
// ^
Use square brackets:
var editor_data = CKEDITOR.instances[INSTANCE_NAME].getData();

Categories