JS three dot operator in Array [duplicate] - javascript

This question already has answers here:
JavaScript (ES6): Using spread operator inside conditional expression (?-operator) [duplicate]
(1 answer)
Spread syntax ES6 with statement
(2 answers)
Closed 17 days ago.
I am wondering what does this three dot operator do in this case:
const csv = [
columns
...data
].map((row) => {
return Object.values(row).join(",");
}).join("\n");
I am trying to convert data to CSV, and if I assign data in the array without three dots operator like this:
const csv = [columns, data].map ...
It returns [object Object], while the one with three dot operators returns the correct data.
What does the operator do here?
I want to add a ternary operator but it seems like it's prohibited with a three dots operator.
what I want to achieve:
const csv = [
columns
(condition) ? ...anotherData : ...data
].map ...

Move the spread syntax (...) before the conditional operator.
const csv = [columns, ...condition ? anotherData : data];

Related

... Spread operator with already an array as parameter [duplicate]

This question already has answers here:
Spread Syntax vs Rest Parameter in ES2015 / ES6
(11 answers)
What is the meaning of "foo(...arg)" (three dots in a function call)?
(4 answers)
Closed 1 year ago.
I have this working code (puppeteer) :

async function extractedEvaluateCall(page) {
await page.waitForXPath(xpath);
const links = await page.$x(xpath);
const results = await page.evaluate((...links) => {
return links.map(e => e.innerText);
}, ...links);
}
What does the notation ... does here ?
I tried without, it doesn't work:
UnhandledPromiseRejectionWarning: TypeError: Converting circular structure to JSON Are you passing a nested JSHandle?
links is already an array, why the need of spread operator ?

need reference for documentation on ternary operator using push [duplicate]

This question already has answers here:
When is the comma operator useful?
(15 answers)
Closed 1 year ago.
I have the following:
let currentLocalStorage = [];
currentLocalStorage = (initialLoad) ? JSON.parse(localStorage.getItem('tasks')): (currentLocalStorage.push(taskInput.value),currentLocalStorage)
which works but I would like to get a reference or documentation for the following:
: (currentLocalStorage.push(taskInput.value),currentLocalStorage)
so basically we are pushing on to the array and then defaulting to the array. I was surprised that we can do this and was wondering where one we look for the documentation
This is using the comma operator. Because .push() returns the new length of the array, you want to make sure you don't assign that to currentLocalStorage, so you use the comma operator to have that expression evaluate to currentLocalStorage.
So it effectively becomes currentLocalStorage = currentLocalStorage in that case, except now the array has one more item thanks to .push().

How to access a particular path/adress inside an object? [duplicate]

This question already has answers here:
access object through dot-syntax string path
(2 answers)
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 2 years ago.
I am having a problem which I think I might have figured out before how to do it but I can't remember now and can't figure it out.
Let's say we have an object thats a few levels deep, meaning it has as values other objects which also have as some of the values objects and so on.
Now how could I make a function to which I pass the object and and adress inside it and I can access the value at that location inside the function like this:
const getValueAtAdress = (object, 'country.city.rules') => {
return //here I need to return the value at object.country.city.rules.
}
Am I missing something obvious?
I thought I'd mention here for posterity that what helped me was the answer using the reduce which is exactly what I used before but I could not remember:
Example that I am using for my particular problem:
let stateLocation = address.split('.').reduce((acc, cur) => acc[cur], state);
Your code shows a function declaration but you can't declare an argument name in quotes
You can however call a function and pass a string.
In that case, you just need to split the string into an array and then loop over that array, building up a "chained" set of string indexes that can be passed to the object. The String.split() and Array.reduce() methods are the key.
let obj = {
county: {
city: {
rules: "Strict"
}
}
};
const getValueAtAddress = (object, countyCityRules) => {
// Split the string at the dots to form an array...
// The loop over that array and reduce it with an
// accumulator that is then applied to the object.
return countyCityRules.split(".").reduce((acc, cur) => acc[cur], obj);;
}
console.log(getValueAtAddress(obj, "county"));
console.log(getValueAtAddress(obj, "county.city"));
console.log(getValueAtAddress(obj, "county.city.rules"));

Javascript: Create dictionary from array of strings [duplicate]

This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 3 years ago.
I have an array of strings that I get from an endpoint and I need to convert it to key-value pairs for the frontend to display them correctly. I have tried different concepts such as reduce and map but have not been able to get it working successfully. I assume it might be one-liner for someone familiar with FE but has taken forever for a BE person like me.
Here is what I have tried:
var input = ['quiz1', 'quiz2'];
const mapping = input.map(x => {"id":x, "label":x};);
console.log(mapping);
I am expecting an output of the format
[{"id":"quiz1", "label":"quiz1"}, {"id":"quiz2", "label":"quiz2"}]
Thanks for looking!
It's simply two syntax errors:
var input = ['quiz1', 'quiz2'];
const mapping = input.map(x => ({"id":x, "label":x}));
console.log(mapping);
Firstly, no semicolon in a un-braced arrow function body.
This is invalid: (() => 3;). This is valid: (() => 3).
Secondly, wrap return obj in ().
This is invalid: () => {x: 3}. This is valid: () => ({x: 3}).

Unfamiliar use of square brackets during multiple variable declaration in Javascript [duplicate]

This question already has answers here:
Multiple assignment in JavaScript? What does `[ a, b, c ] = [ 1, 2, 3 ]` mean?
(4 answers)
Closed 5 years ago.
I'm a beginner to Javascript and encountered this syntax usage(simplified):
var testString ="firstName, lastName";
var [a,b] = testString.split(", ");
My question is what typeof variable a & b then becomes at line2?
My simplistic investigation seems to indicate a & b are assigned respective string values.
But what goes on under the hood? why do we use square brackets [] here? Isn't an array returned & created in the process by .split()? Otherwise, what objects were created in the background?
Links to understand this style of declaration for [a,b] would also be welcomed.
But what goes on under the hood?
// You declare a string variable
var testString = "firstName, lastName";
// Split method help you to divide the string value according with the
//indicated separator, in this examle the comma
var [a,b] = testString.split(", ");
The destructuring assignment syntax is a JavaScript expression that
makes it possible to unpack values from arrays, or properties from
objects, into distinct variables.
Since the split function returns an array, with the var [a,b] = array
you are assigning the value in index order, in the example:
console.log(a); // 'firstName'
console.log(b); // 'lastName'
And they are simple string variables. You may want to vist the links below:
Destructuring asignation
split function
Further resources: Since you have mentioned you are beginning with JS, I suggest you to read books mentioned in this magnific post
This is destructuring assignment. It resembles the pattern-matching found in many functional languages.

Categories