Array destructuring into object assignment in a single instruction - javascript

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);

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.

Cleanest way to set multiple object keys

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'}

ES6 spread element - default value

I need to set an empty object as a default value if the array I'm passing in is empty. Something like:
var obj = { documents: [...question.documents] || [{}] }
I fixed it using a condition, but I want to know if there is a better way to achieve that.
if(obj.documents.length === 0) obj.documents.push({})
Since even empty arrays are truthy, I don't think there's any great elegant solution other than putting an explicit test in there somewhere. Ternaries are more terse than if statements, though:
const question = { documents: [] };
const { documents } = question;
const obj = { documents: documents.length !== 0 ? documents : [{}]}
console.log(JSON.stringify(obj));
Here's another possibility:
const question = { documents: [] };
const [firstElm = {}, ...otherElms] = question.documents;
const obj = { documents: [firstElm, ...otherElms] };
console.log(obj);
There are a couple of ways to write this in a single expression
Using the ternary operator:
var obj = { documents: [
...question.documents.length
? question.documents
: [{}]
]
};
Using a default value
var obj = { documents: [question.documents[0] || {}, ...question.documents.slice(1)] };
In both cases there's some awkwardness stemming from having to refer to the source multiple times
The spread operator is used inside an empty array. I don't see the
point in using the spread operator here. The objective can be achieved
by using the following.
var obj = { documents: question.documents.length ? question.documents : [{}]}
If the method you have provided is being used, you don't need an or clause, because an empty array also returns a truthy value. So it can be written as the following :-
var obj = { documents: question.documents }
if(!obj.documents.length) obj.documents.push({})
this should suit...
const question = {
documents: [],
};
const obj = {
documents: [].concat(question.documents.length ? question.documents : {})
};
console.log(obj);
The shortest way
const obj1 ={...(true&& {x:1})};
console.log(obj1)
const obj2 ={...(false&& {y:1})};
console.log(obj2)

How to destructure obj[arr[0]] = arr[1]

Given the following code eslint throws a prefer-destructuring error at me:
const params = {};
const splitted = 'key=value'.split('=');
params[splitted[0]] = splitted[1];
How can I use destructuring in the third line?
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Try the below example, it assign value at zero index to key variable and value at first index to value variable.
const params = {};
const [key,value] = 'key=value'.split('=');
params[key] = value;
console.log(params);

str.split to json with names

I have taken a string that is "title:artist" and used str.split :
res = song.split(":");
Which gives me an output of :
["Ruby","Kaiser Chiefs"]
I was wondering how I could add name to this so that it appears as :
["name":"Ruby", "artist":"Kaiser Chiefs"]
var res = song.split(':');
var jsonString = JSON.stringify({ name: res[0], artist: res[1] });
You can find more information about how to use JSON.stringify here but basically what it does is takes a JavaScript object (see how I'm passing the data as an object in my answer) and serializes it into a JSON string.
Be aware that the output is not exactly as you have described in your question. What you have is both invalid JavaScript and invalid JSON. The output that I have provided will look more along the lines of {"name":"Ruby", "artist":"Kaiser Chiefs"}. Notice how there is {} instead of [].
["name":"Ruby", "artist":"Kaiser Chiefs"] isn't a valid format I guess you want to create an object so you could use just the split like :
var my_string = "Ruby:Kaiser Chiefs";
var my_string_arr = my_string.split(':');
var my_object = {'name': my_string_arr[0],"artist": my_string_arr[1]};
console.log(my_object);
Or also assign the values to the attributes separately like:
var my_string = "Ruby:Kaiser Chiefs";
var my_string_arr = my_string.split(':');
var my_object = {};
my_object.name = my_string_arr[0];
my_object.artist = my_string_arr[1];
console.log(my_object);
Hope this helps.
What you're looking for is: Object. Here is how you do it:
var str = "Ruby:Kaiser Chiefs";
var res = str.split(':');
// this is how to declare an object
var myObj = {};
// this is one way to assigne to an object
// using: myObj["key"] = value;
myObj["name"] = res[0];
// this is another way to assign to an object
// using: myObj.key = value;
myObj.artist = res[1];
console.log(myObj);

Categories

Resources