Call variable from string value with React Redux [duplicate] - javascript

This question already has answers here:
Convert string to variable name in JavaScript
(11 answers)
"Variable" variables in JavaScript
(8 answers)
Closed last month.
Still learning React, having trouble finding the solution on this one.
I have a series of arrays in the initialState of a redux slice, i.e
const initialState = {
sprites: {
one: [1, 2, 3],
two: [4, 5, 6],
three: [7, 8, 9]
}
}
In the app, when the user clicks on a particular button, among other things, I need to get the length of the relevant array.
Here's an example of the app:
<Component onClick={() => {dispatch(checkArray("one"))}/>
And the reducer:
checkArray: (state, {payload}) => {
var arrayLength = state.sprites.{payload}.length;
console.log(arrayLength);
}
Obviously this does not yield the desired effect. Using {payload} just throws an error. But how do I convert the payload in a way that will yield the numerical value of the length of the state.sprites.one.length array?
Thanks

Use bracket notation.
state.sprites[payload].length;

If you want to access a property of an object using a variable, use the square bracket notation. Use square brackets with the payload variable instead of dot notation and curly braces, like this:
checkArray: (state, {payload}) => {
var arrayLength = state.sprites[payload].length;
console.log(arrayLength);
}

Related

How to access nested object with numeric key? [duplicate]

This question already has answers here:
Object property name as number
(6 answers)
Closed 3 years ago.
I am working on an API which consists of nested objects with numeric keys. Here is the data:
{ "data": {"0":{"name":"kp"},"1":{"name":"josan"}}
I am wondering how can a key be numeric. As per my knowledge it should not possible.
axios.get(``)
.then( res => {const persons = res.data;
this.setState({persons});
render(){return ({this.state.persons.data."1".name})
I want to access name of 1.
Use bracket notation like so:
this.state.persons.data["1"].name
You can't use numbers usually because all JavaScript object keys are strings - and it gives you a syntax error if you try to use a number in dot notation:
const obj = { 1: "foo" };
console.log(obj..1);
However, because of a quirk of implicit conversion, numbers in bracket notation works fine:
const obj = { 1: "foo" };
console.log(obj[1]);
You can use [] (bracket) notation
var a={ "data": {"0":{"name":"kp"},"1":{"name":"josan"}}}
console.log(a.data[0].name)
console.log(a.data[1].name)
If { "data": {"0":{"name":"kp"},"1":{"name":"josan"}} is the response from the API, and you are already doing this: const persons = res.data;
Then to get the name you need to use this.state.persons['1'].name.

I just started my journey in Javascript, am finding this array question bit tricky and confusing. Please someone should help me out here [duplicate]

This question already has answers here:
why javascript const keyword is not working in array?
(3 answers)
Closed 3 years ago.
const numbers = [1,2,3,4,5]
let luckyNum = numbers.pop()
What will be the value of numbers?
Hint: numbers is stored in a constant not a variable
From the MDN you can read:
Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through reassignment, and it can't be redeclared.
In you particular case the numbers variable holds a reference to the array and that reference will remain "constant", not the array itself. As you can check on next example:
const numbers = [1,2,3,4,5];
let luckyNum = numbers.pop();
console.log("luckyNum:", luckyNum, "numbers:", numbers);
// Now, next line will trhow an error, because we are
// trying to do a reassingment on a const variable:
numbers = [];
In the particular case you are interested, you can use Object.freeze() to prohibit changes on an array of primitives values:
const numbers = [1, 2, 3, 4, 5];
Object.freeze(numbers);
// Now, next line will thrown an error.
let luckyNum = numbers.pop();
console.log("luckyNum:", luckyNum, "numbers:", numbers);
I Hope this clarifies your doubts.
Even though it's a const, it will be modified and the new value will be [1,2,3,4].

JS destructuring complicated statement? [duplicate]

This question already has answers here:
Javascript object bracket notation ({ Navigation } =) on left side of assign
(5 answers)
What is destructuring assignment and its uses?
(3 answers)
Closed 3 years ago.
let messages = {
1: {
id: '1',
text: 'Hello World',
userId: '1',
},
2: {
id: '2',
text: 'By World',
userId: '2',
},
};
// what does this statement do?
const {
[1]: message,
...otherMessages
} = messages;
console.log("other messages: ", otherMessages);
We didn't have a variable otherMessages, so how does the rest syntax work on this variable? What does the above statement do in general, it's somewhat complicated?
This is a destructuring assignment. See MDN fore more information
On the left side of the = sign, you declare the variables to be destructured, and on the right side the variable to desctructure.
Doing this, you are declaring two variables message and otherMessages:
const { [1]: message, ...otherMessages } = messages;
and you are extracting the value of key 1 into message, and the rest of the messages object will be desctructured into otherMessages.
Since messages contains two entries with keys 1 and 2, otherMessages will be an object containing the remaining keys, which is only key 2.
When trying to assign the variable otherMessages, the runtime checks to see where it is declared. As it goes up the scopes if it reaches the top level, in this case window, it will declare the variable and then assign to it using the destructuring syntax.
Think about this another way: if you were to do something like this:
otherMessages = [1, 2]
Without declaring otherMessages as a var before hand, wouldn’t the runtime declare the variable for you?

Syntax - what does square brackets around a variable declaration mean [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.
Take the following line of code
const [component] = router.getMatchedComponents({ ...to })
Could anyone advise what the square brackets around component means here? I have tried to google this but struggling to find an answer
It's called Destructuring assignment, and it's used to unpack the values of an array and assign them to new variables.
So here in your code:
const [component] = router.getMatchedComponents({ ...to })
You are assigning to the component variable the first element held in the array that will be returned by router.getMatchedComponents({...to}), where to is an array-like structure turned into object using the spread operation.

What is this syntax 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.
Take the following line of code
const [component] = router.getMatchedComponents({ ...to })
Could anyone advise what the square brackets around component means here? I have tried to google this but struggling to find an answer
It's called Destructuring assignment, and it's used to unpack the values of an array and assign them to new variables.
So here in your code:
const [component] = router.getMatchedComponents({ ...to })
You are assigning to the component variable the first element held in the array that will be returned by router.getMatchedComponents({...to}), where to is an array-like structure turned into object using the spread operation.

Categories

Resources