This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 3 years ago.
Following is my code which is giving Parsing error -
Code -
const { dataArr, anotherDataArr } = this.props.data
const myArr1 = dataArr.map(item => {'label': item.name,'value': item.code})
const myArr2 = anotherDataArr.map(item => { 'label': item.name, 'value': item.code})
this.setState({
newArr1: myArr1,
newArr2: myArr2,
})
myArr1, myArr2 should be an array of objects but I am getting parsing error. Let me know what silly mistake I am making here.
When you need to implicitly return an object from an arrow function wrap that object in (). Wrapping with () will make make the object expression. Without () {} will considered as block.
According to Returning object literals:
The code inside braces {} is parsed as a sequence of statements
Remember to wrap the object literal in parentheses().
const myArr1 = dataArr.map(item => ({'label': item.name,'value': item.code}))
const myArr2 = anotherDataArr.map(item => ({ 'label': item.name, 'value': item.code}))
Related
This question already has answers here:
What does this symbol mean in JavaScript?
(1 answer)
What do square brackets around a property name in an object literal mean?
(2 answers)
Closed 2 months ago.
const handleChange = (event) => {
const { name, value } = event.target;
Here is [name] that is inside the square bracket. I know what it's doing but I just want to know what was the logic under the hood to use this logic?
setFormFields({ ...formFields, [name]: value });
console.log(formFields);
};
If it's array destructuring why and how is it working and why not object destructuring and what is the reason behind using this logic?
In your first example, const { name, value } = event.target; is object destructuring, pulling the name and value properties off of event.target;
While your second example looks the same, it's the opposite - instead of destructuring an object into variables you're creating a new object. Somewhere above that line, there's a variable called name.
You can think of the example like this:
const name = 'someKey';
const value = 'someValue';
const formFields = { keyOne: 'one' };
const newObject = { ...formFields, [name]: value }; // { keyOne: 'one', someKey: 'someValue' };
This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
Closed 3 years ago.
Its known that someone can make a one-line array function like this to return the single value:
var func = (x) => x + 1 //func(2) == 3
and you can also make multi-line array-functions, whose values need to be manually returned:
var funcMultiline = (x) => {
var result = 1;
result += x;
return result;
}
funcMultiline(4) == 5; //true
So the question:
let's say I want to return a new object in one line, if I use the brackets, then the array-function is treated like a multi-line function, and doesn't actually return the object-literal. Is there any direct way to create an object literal in, lets say, a map function? Like:
[...Array(25)].map(e => {x: 5, y:10}) //this is a syntax error, but how can I make this work
Returning object literals using the concise body syntax params => {object:literal} will not work as expected.
You have to wrap the object literal with parenthesis:
var res = [...Array(25)].map(e => ({x: 5, y:10}))
console.log(res);
This question already has answers here:
Javascript object bracket notation ({ Navigation } =) on left side of assign
(5 answers)
Closed 4 years ago.
I'm new in react and I'm reading some code i found this line of code:
const {intl: { formatMessage }, } = this.context
is a const declaration but i don't understand
I know is JS ES6 but i don't understand what is it for?
How can I check the value of this const?
thanks
As people already answered. This is object destructuring
Simple example: const contact = {name: 'John', email: 'john#doe.com'}
With ES6 you can do const {email} = contact; //email = contact.email
In case you want to name the variable differently, it would be:
const {email: mailbox} = contact //equivalent to mailbox = contact.email;
Back to the original question: {intl: { formatMessage }, } = this.context
=> {formatMessage} = this.context.intl => formatMessage = this.context.intl.formatMessage
The code that you have is, actually a representation of the following code,
const formatMessage = this.context.intl.formatMessage
You can read about object destructuring to know more about it.
This simply means that this.context contains a structure similar to this
this.context = {
intl:{
formatMessage: // This has a value let's say "Hello"
},
//Other key-value pairs could be contained in the context object }
This line of code is a shorthand syntax telling you that only the formatMessage property which can be found inside "intl" should be retrieved from the large object called "this.context"
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 5 years ago.
Is there a better way to do the following. consider this code:
this.state = {
dates: [
{date: '1st', matches:[]},
{date: '2nd', matches:[]},
{date: '3rd', matches:[]},
{date: '4th', matches:[]},
{date: '5th', matches:[]}
]
}
addToDates = () => {
let dates = this.state.dates;
const matches = this.props.matches;
matches.forEach(function(match){
dates.forEach(function(date){
if (match.date == date.date){
this.setState({dates: this.state.dates.concat(match)})
}
})
})
}
what i am trying to do is iterate through 2 arrays and if i find a match that has the same date as a date then i want to add it to the matches array.
2 problems, firstly is there a better way to compare 2 arrays rather than iterating through both?
secondly i get cant read setState of undefined even though i have:
this.addToDates = this.addToDates.bind(this) bound it in my constructor. i thought arrow functions solved that scoping too?
You need to use arrow functions in your addToDate method. You don't actually have to bind addToDates in your constructor as you are using an arrow function as a class property.
The value of this when you are using this.setState is different if you don't use an arrow functions for your forEach loops.
addToDates = () => {
let dates = this.state.dates;
const matches = this.props.matches;
matches.forEach(match =>{
dates.forEach(date =>{
if (match.date == date.date){
this.setState({dates: this.state.dates.concat(match)})
}
});
});
As per MDN
Until arrow functions, every new function defined its own this value
(a new object in the case of a constructor, undefined in strict mode
function calls, the base object if the function is called as an
"object method", etc.). This proved to be annoying with an
object-oriented style of programming.
An arrow function does not create its own this, the this value of the
enclosing execution context is used.
This question already has answers here:
ECMAScript 6 arrow function that returns an object
(6 answers)
What does the arrow function with a () after means? [duplicate]
(3 answers)
ES6 Fat Arrow and Parentheses `(...) => ({...})` [duplicate]
(2 answers)
What does arrow function '() => {}' mean in Javascript? [duplicate]
(2 answers)
Closed 5 years ago.
I've seen JavaScript code such as this:
let a = () => ({ id: 'abc', name: 'xyz' })
What do the parentheses ( … ) wrapping the object refer to in this instance? Is it a shorthand for return?
No. Those parentheses produce an object literal. Arrow functions have many syntaxes, one of which is:
( … ) => expression
This will implicitly return an expression, for example:
() => 1 + 1
This function will implicitly return 1 + 1, which is 2. Another one is this:
( … ) => { … }
This will create a block to house multiple statements if you don't want to implicitly return an expression, and if you want to do intermediate calculations or not return a value at all. For example:
() => {
const user = getUserFromDatabase();
console.log(user.firstName, user.lastName);
}
The problem arises when you want to implicitly return an object literal. You can't use ( … ) => { … } because it'll be interpreted as a block. The solution is to use parentheses.
The parentheses are there for the { … } to be interpreted an object literal, not a block. In the grouping operator, ( … ), only expressions can exist within them. Blocks are not expressions but object literals are, thus an object literal is assumed. Thus, instead of creating a block, it will use this syntax:
( … ) => expression
And implicitly return an object literal. Without the parentheses, it will be interpreted as labels and strings, not keys and values of an object literal.
let a = () => {
id: 'abc', //interpreted as label with string then comma operator
name: 'xyz' // interpreted as label (throws syntax error)
}
The comma here would be interpreted as the comma operator, and since the operands must be expressions, and labels are statements, it will throw a syntax error.
It allows you to create an expression, so
let a = () => ({ id: 'abc', name: 'xyz' })
specifies that a when invoked, returns the enclosed object
If you remove the () in this case, it will throw an error because it is not a valid function body statement, because the {} in let a = () => { id: 'abc', name: 'xyz' } are interpreted as the boundaries of a statement, but the content inside is not valid if you look at it.
let a = () => {
id: 'abc', /* Not valid JS syntax */
name: 'xyz'
}