Confusion about const declaration inside object - javascript

I came across this piece of code here, and I noticed that const data is declared inside the brackets. I thought you had to use the key: value format inside the brackets when creating an object. How does this work?
data = {
const data = await d3.tsv("https://gist.githubusercontent.com/mbostock/8033015/raw/01e8225d4a65aca6c759fe4b8c77179f446c5815/unemployment.tsv", (d, i, columns) => {
return {
name: d.name.replace(/, ([\w-]+).*/, " $1"),
values: columns.slice(1).map(k => +d[k])
};
});
return {
y: "% Unemployment",
series: data,
dates: data.columns.slice(1).map(d3.utcParse("%Y-%m"))
};
}

That is not valid javascript. The reason it works is that Observable has its own syntax. It's deliberately designed to be similar to javascript, but it isn't actually javascript. You can read more about this here:
https://observablehq.com/#observablehq/observables-not-javascript

The code above is not a valid javascript code.
observableHQ is using its own parser to achieve that https://github.com/observablehq/parser the code is translated to the following:
const chart = (arguments) => {
// code...
}

Related

When to use curly brackets vs curved brackets in React

I'm currently taking an online course to learn React and I'm confused as to when I should be using { vs (.
I have 3 files:
App.js
const App = () => {
card-list.component.jsx
const CardList = ({ monsters }) => (
card.component.jsx
const Card = ({ monster }) => {
This is the code that currently works. Notice that on the second code the last character used is (. I thought of changing it to { to make it consistent with the other files but somehow the card list no longer shows up on the page although I didn't get any compile errors.
Can someone explain this to me and tell me when I should use one over the other?
This essentially is a feature of arrow functions in js.
const myArrowFunc = ({key1}) => ("Hello there! " + key1);
is essentially the same as
const myArrowFunc = ({key1}) => { return "Hello there! " + key1 };
when you leave out the curly brackets, the return is implicit.
When you include the curly brackets, you must explicitly use the return statement.
const someObj = { key1: "value1" };
const someReturn = myArrowFunc(someObj);
console.log(someReturn); // logs "Hello there! value1" to the console
()=>{} is the syntax of arrow function
When an arrow function only contains one line that return a value, e.g.:
() => {
return 1;
}
it can be simplified to
() => 1
Now what if you want to return an object directly? i.e. how to simplify
() => {
return { foo: "bar" }
}
Since an object also use {}, you cannot write {foo: "bar"} directly after the arrow as it will be treated as the function body. Wrapping the object within () solves the problem since a () chunk must be an expression. The above example can be simplified to
() => ( { foo : "bar" } )

Is there a way to not include methods when converting an object to a json?

Right now, I'm trying to convert a object to a json, but the object has methods in it.
One common solution I've found is storing the function in the json, but that wouldn't work for me (mainly because that would totally break updating)
I think it will be easier to reinitialize the function every time the program is reloaded. What would be the best way to exclude functions when stringifying to json, but including the functions when the json is parsed?
Extra note: some of the functions are stored in arrays and other objects
Edit:
Current code to load json data:
var loadData = JSON.parse(window.localStorage.getItem("slotAuto"));
G = {
...G,
...loadData
};
Current code to save json data:
var toSave = JSON.stringify(G, G.ReplaceNull);
console.log(toSave);
window.localStorage.setItem("saveGame", toSave);
Replace Null function:
if (value == null) {
return undefined;
};
return value
Example object:
{
functionList: [function () {
console.log("do something")
}]
}
Example output:
{
"functionList": [null]
}

Odd javascript notation - what does it mean? [duplicate]

This question already has answers here:
Javascript Object destructuring and default parameters combined
(3 answers)
Closed 2 years ago.
Just looking over a cool tutorial and there was a notation that I didn't completely understand and having a hell of a time trying to google it.
async function mapEffect({ leafletElement: map } = {}) {
let response;
try {
response = await axios.get(‘https://corona.lmao.ninja/countries’);
} catch(e) {
console.log(`Failed to fetch countries: ${e.message}`, e);
return;
}
// this next line here is the one confusing me:
const { data = [] } = response;
}
Reading on, it appears that data is just an array - any reason it is written like this? Can anyone explain in layman's terms why you would write something this way? I never stop learning... Thank you!
const { data = [] } = response;
is equal to
// [] is default value if response.data is empty
const data = response.data || [];
What that piece of code is doing is destructuring an object.
Destructuring lets you bind variables to different properties of an object. When you specify the property being bound, it will then be followed by the variable you are binding its value to.
Here is a basic example:
const { foo, bar } = { foo: "hello", bar: "world" };
console.log(foo);
console.log(bar);
//1st letter
console.log(foo[0]);
console.log(bar[0]);
In your case it has a default value as fallback ( [] an array in case your response comes empty)
You can read more about it here

Turn a for loop on an object into a .map

I have been told my function:
for (const key of Object.keys(temp)) {
this.sessionData.push(temp[key]);
}
Must now use a .map instead,
I have tried this below:
Object.keys(temp).map(function(key) {
this.sessionData[key];
})
But 1 I don't know if it's actually accurate, and also, it cant access the data outside of the scope of the function it is in, here is the whole function below:
public sessionData;
sessionDates(sessionsData) {
const temp = {};
this.sessionData = [];
sessionsData.forEach(session => {
const date = moment(session.startDatetime).format('DDMMYYYY');
if (temp[date]) {
temp[date].push(session);
} else {
temp[date] = [session];
}
});
Object.keys(temp).map(function(key) {
this.sessionData[key];
})
TRYING TO USE THIS BELOW... session data is undefined, it can't access out of the scope?
Object.keys(temp).map(function(key) {
this.sessionData[key];
})
But this works..
for (const key of Object.keys(temp)) {
this.sessionData.push(temp[key]);
}
So this new .map method can't access anything out of its scope.. sigh!
If anybody can help that would be amazing! Thanks!
In Javascript all functions can access variables from outside (called "higher scope") - it's one of the strengths of the language and is called "capture".
The reason your code is failing is because it's using this.sessionData inside a function declaration, which cases problems because this in javascript is... somewhat complex. But you don't need it!
You also need to make sure you return the value you want to output. Here's how I would write it:
this.sessionData = Object.keys(temp).map(key => temp[key]);

encodeURIComponent in React

I have a react function returning a promise from axios, and I need to encode an equation type string is being passed to it.
const { equation } = this.state;
axios.post(`${this.state.rootUrl}/integrate`, { equation }).then(some other code)
I want to encode the string equation before passing it to the API for a query.
I have tried the following but it didn't work.
axios.post(`${this.state.rootUrl}/integrate`, { encodeURIComponent(equation) })
I also tried this:
const { equation } = this.state;
const { test } = encodeURIComponent(equation);
axios.post(`${this.state.rootUrl}/integrate`, { test }).then(some other code)
This also didn't work.
Here's the full code of the function where I'm trying use this:
handleSubmit = (e) => {
e.preventDefault();
const { equation } = this.state;
// const { test } = encodeURIComponent(equation);
axios.post(`${this.state.rootUrl}/integrate`, { equation })
.then((response) => {
const data = response.data;
this.setState({ data: data });
console.log(equation);
if (data != null) {
this.setState({input: data.response[0]});
}
}
}
In your original example, you're using the shorthand syntax for setting object properties - the following two lines of code are equivalent:
{ equation }
{ equation: equation }
Your second two examples don't do the same thing! In example two, you're trying to use the shorthand with a method call, which won't work. In example three, you're trying to destructure the return value of encodeURIComponent(equation), which also won't work (it returns a string).
Fawaz's first example almost works, but there's a subtle difference in behavior - because they've named the variable test, the key of the object being passed to Axios will also be test. Remember, these are equivalent:
{ test }
{ test: test }
Presumably, your API is expecting something called equation, not test, so this won't work.
To get the right behavior, you should make sure the object you're passing has the right key:
const test = encodeURIComponent(equation);
axios.post(`${this.state.rootUrl}/integrate`, { equation: test })
// or
axios.post(`${this.state.rootUrl}/integrate`, { equation: encodeURIComponent(equation) })
There seems an issue in using the shorthand. Try like this :
const test = encodeURIComponent(equation); // no braces here
axios.post(`${this.state.rootUrl}/integrate`, { test }).then(some other code)
or
axios.post(`${this.state.rootUrl}/integrate`, { test: encodeURIComponent(equation) })

Categories

Resources