Reputation: 6944
I have this react code which set the state::
onMoveUp={(ids: SelectedIdMap) => {
this.setState({
xyz: {
...this.state.xyz,
[tt]: [
...this.state.xyz[tt].filter(a => (a.id in ids)),
...this.state.xyz[tt].filter(a => !(a.id in ids)),
],
},
});
}}
This code changes the index of passed array element (ids) to the top of array.
Current state is like this::
{"51f6c052-b218-45ce-b3db-c9b95249e03a":[{"id":"11553dc4-d194-476c-9e05-aaac28ea3e76","prediction":"India–Japan relations","confidence":1},{"id":"3f76ce1d-a821-4418-a332-3285176ae456","prediction":"Japan Democratic Party (1954) politicians","confidence":1},{"id":"031d3913-984a-4af7-aaa3-73e23c206ff1","prediction":"Japan–Taiwan relations","confidence":1}]}
I am unable to understand what [tt] means in this code & how it is updated.
ids = 11553dc4-d194-476c-9e05-aaac28ea3e76 in the parameter.
It is silly question but please help me understand it.
Upvotes: 0
Views: 1243
Reputation: 104529
This is nothing but Computed property name
concept in js
. That means we can use any valid js expression to compute the property name at run time.
As per MDN Doc:
Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name. This is reminiscent of the bracket notation of the property accessor syntax.
Its helpful to write a reusable code instead of hardcoding the values.
Check this snippet:
var obj = {"1234": 1, "3412": 2},
a = "34", b = "12";
var newObj = {
[a+b]: obj[a+b],
[b+a]: obj[b+a],
[10+20+30]: 60
}
console.log('newObj = ', newObj);
Check this snippet how its working in your case:
var obj = {"a": 1, "b": 2};
function update(key, value){
return {[key]: value};
}
obj = Object.assign({}, obj, update('a', 10));
obj = Object.assign({}, obj, update('b', 20));
console.log('bj = ', obj);
Upvotes: 1