I’m trying to add new items to an array of an object that resides in another object of a state. Pretty nested.
So I tried the following way…
JavaScript
x
10
10
1
// The initial data
2
[options, setOptions] = useState({
3
name: 'Name goes here'
4
type: 'type goes here'
5
series : [{
6
type: 'series type',
7
label: 'series label'
8
9
})
10
Now I want to add another object inside the object of series array with useEffect(). And I tried:
JavaScript
1
12
12
1
useEffect(() => {
2
// other functionalities goes here
3
setOptions({
4
options, // for copying previous data outside of series
5
series: [{
6
options.series, //this is for copying previous data of series
7
tooltip: {
8
enable: true,
9
}]
10
})
11
}, [refreshData])
12
The way I’m copying ...options
works absolutely fine, But when I try to copy ...options.series
it adds a new copied object inside the object of series array like the following:
JavaScript
1
10
10
1
{
2
name: 'Name goes here' //fine
3
type: 'type goes here' //fine
4
series: [{
5
{type: 'series type', label: 'series label'}, //not fine
6
tooltip: {enable: true} //not fine
7
//what I want is: to have previous object data and tooltip appended as another item
8
}]
9
}
10
The way I want the object to be is:
JavaScript
1
10
10
1
{
2
name: 'Name goes here' //fine
3
type: 'type goes here' //fine
4
series: [{
5
type: 'series type',
6
label: 'series label'
7
tooltip: {enable: true}
8
}]
9
}
10
Can Anybody help me regarding this. I would appreciate any help.. Thanks
Advertisement
Answer
here is sample of what you are trying to achieve .
JavaScript
1
22
22
1
const d = {
2
name: 'Name goes here',
3
type: 'type goes here',
4
series : [{
5
type: 'series type',
6
label: 'series label'
7
}]
8
}
9
10
11
const newD = {
12
d,
13
series: [
14
{
15
d.series[0], // problem is here
16
tooltip: {
17
enable: true,
18
}
19
}
20
]
21
}
22
console.log (newD)