Cleanest way to set multiple object keys - javascript

Hi I was working on a text parser and I was wondering if there was a clean to rewrite the following code. Concerning the way that an object's properties are set.
//In the real case the parser returns varying result based on the param
const parserResult = {'value':2,'syntaxError':false,'NaNError':false}
const {value,syntaxError,NaNError} = parserResult
const param = {someProperty:'any value'} //can have any properties
//the problem under here
param['value'] = value
param['syntaxError'] = syntaxError
param['NaNError'] = NaNError
console.log(param)
Setting three properties like that one after an other is not all that eloquent does anyone now a cleaner solution? Thanks in advance.
(complete code to test under here)
const parseParam = param => {
//In the real case the parser returns varying result based on the param
const parserResult = {'value':2,'syntaxError':false,'NaNError':false}
const {value,syntaxError,NaNError} = parserResult
param['value'] = value
param['syntaxError'] = syntaxError
param['NaNError'] = NaNError
return param
}
const parameters = [{someProperty:'test'},{someProperty:'someValue'}]
const parsedParameters = parameters.map(parseParam)
console.log(parsedParameters)

You should use spread operator for this kind of stuff.
It will look like this:
const param = {...parserResult, someProperty:'any value'}

Related

Get JSON value by using variables on the 2nd level of depth

I have a .json file like this:
{
"width": 700,
"height": 1382,
"dataID": {
"id1": "54321",
"id2": "12345"
}
}
I need to get value of id1 or id2 keys dynamically (using a variable). I use Cypress function cy.read() and by using definite strings it works good:
cy.readFile(pathToConfigFile).then(($file) => {
const id1value = $file.dataID.id1;
});
But how to wrap this expression into variable containing id1?
There is a similar question : Dynamically access object property using variable
However the solution proposed there refers only to the first level of depth. With square brackets I can get the following values:
cy.readFile(pathToConfigFile).then(($file) => {
const customVariable = "dataID";
const id1value = $file[customVariable];
});
But in case of it returns id1value = undefined:
cy.readFile(pathToConfigFile).then(($file) => {
const customVariable = "dataID";
const id1 = "id1";
const id1value = $file[customVariable][id1];
});
You will need to check the value of the variable after the first check so you know whether you can read the second-level value.
cy.readFile(pathToConfigFile).then(($file) => {
const customVariable = "dataID";
const id1 = "id1";
const idValues = $file[customVariable];
return idValues ? idValues[id1] : undefined;
});
Instead of undefined you can return some default value if you prefer.
There are also packages which can be used to do this automatically for you, such as lodash's _.get() method.

How to set this value as variable?

I want to set the value of this part (shown in imagehere) as a variable?
Just put like var myvariable = data.events, and It should works, If you have any question just comment.
You can do it in several ways:
const data = {event: 'some user event'};
// 1. dot notation
const userEvent1 = data.event;
// 2. Bracket Notation
const key = 'event'
const userEvent2 = data[key]; // or just data['event']
// 3. destructuring
const { event } = data;
console.log('userEvent1:', userEvent1)
console.log('userEvent2:', userEvent2)
console.log('event:', event)
I will attach useful articles:
https://codeburst.io/javascript-quickie-dot-notation-vs-bracket-notation-333641c0f781
https://dmitripavlutin.com/javascript-object-destructuring/
You Can Do It With Pretty Much a lot of ways Like
But the Most Simplest Way is using dot notation
const event = data.event

Objects: Value always undefined

I am working on some keybinding functionality and came across something that is quite confusing to me.
I am doing some regex validation against the user defined keybinding pattern and would then like to assign the pattern as key and value to definedKeys:
const definedPattern = ['a', 'b']
let definedKeys = {}
const bindKeys = () => {
const charKey = (String(definedPattern[0]) + String(definedPattern[1])).match(/^[a-zA-Z]{2}$/)
if (charKey) {
definedKeys[charKey.input[0]] = definedKeys[charKey.input[1]]
}
console.log(definedKeys)
}
bindKeys()
Use definedKeys instead of definedCharKeys as it is not declared neither initailized
Assigning value directly to key instead of refrencing value from definedKeys because value is not still set and it will be always undefined.
definedKeys = {};
const encodeKey = (pKey) => {
charKey = (String(pKey[0]) + String(pKey[1])).match(/^[a-zA-Z]{2}$/);
if (charKey) {
// charKey.input = 'ab'
definedKeys[charKey.input[0]] = charKey.input[1];
}
}
encodeKey('ab');
console.log(definedKeys);
Isn't it because you don't put anything in definedKeys but instead you put it in definedCharKeys?
As per the code. You are not assigning anything in "definedKeys". You are assigning a value in "definedCharKeys" that's why you are getting undefined for the "definedKeys".
Please post full code where are you calling the function so that developers can provide you solution.

Array destructuring into object assignment in a single instruction

Eslint yells at me about this line because it should be done with array destructuring :
postModel.base64File = formFile.split(',')[1];
I am concerned because I cannot find a way to do this in a single instruction. The best I came up with is the following :
const [, b64] = formFile.split(',');
postModel.base64File = b64;
Is there a way to make this assignment in a single instruction ?
You could destructure to the property directly.
var postModel = {},
formFile = 'a,b';
[, postModel.base64File] = formFile.split(',');
console.log(postModel);
The same with an object and an index as target.
var postModel = {},
formFile = 'a,b';
({ [1]: postModel.base64File } = formFile.split(','));
console.log(postModel);

Javascript: Server sided dynamic variable names

How would I create dynamic variable names in NodeJS? Some examples say to store in the window variable, but I was assuming that is client-side Javascript. Correct me if I'm wrong.
Generally you would do something like:
var myVariables = {};
var variableName = 'foo';
myVariables[variableName] = 42;
myVariables.foo // = 42
In node.js there is the global context, which is the equivalent of the window context in client-side js. Declaring a variable outside of any closure/function/module as you would in plain Javascript will make it reside in the global context, that is, as a property of global.
I understand from your question that you want something akin to the following:
var something = 42;
var varname = "something";
console.log(window[varname]);
This in node.js would become:
var something = 42;
var varname = "something";
console.log(global[varname]);
Just don't know what a bad answer gets so many votes. It's quite easy answer but you make it complex.
var type = 'article';
this[type+'_count'] = 1000; // in a function we use "this";
alert(article_count);
One possible solution may be:
Using REST parameter, one can create an array and add each dynamic variable (REST parameter item) as an object to that array.
// function for handling a dynamic list of variables using REST parameters
const dynamicVars = (...theArgs) => {
let tempDynamicVars = [];
// as long as there are arguments, a new object is added to the array dynamicVars, creating a dynamic object list of variables
for (let args = 0; args < theArgs.length; args++){
const vName = `v${args}`;
tempDynamicVars = [...tempDynamicVars, {[vName]: theArgs[args]}]; //using spread operator
// dynamicVars.push({[vName]: theArgs[args]}); // or using push - same output
}
return tempDynamicVars;
}
// short version from above
// const dynamicVars = (...theArgs) => theArgs.map((e, i) => ({[`v${i}`]: e}));
// checking
const first = dynamicVars("F", 321);
console.log("Dynamic variable array:", first);
console.log(` - ${first.length} dynamic variables`);
console.log(" - second variable in the list is:", first[1], "\n");
console.log(dynamicVars("x, y, z"));
console.log(dynamicVars(1, 2, 3));
console.log(dynamicVars("a", "b", "c", "d"));

Categories

Resources