I am having an object as below
result = [{
"name": "jmd",
"children": [
{
"name": "ppp1",
"children": [
{
"name": "feeder",
"children": [
{
"name": "rmu1",
"children": [
{
"name": "IT1",
"children": [
{
"aname": "Asset123",
"value" : "233"
}
]
}
]
}
]
}
]
}]
I need to detect the change every time the value changes using ngOnchanges
event of Angular 6
.
it seems the angular ngOnchanges
doesn't detect the deeply nested object.I have tried different things like
this.chartData = Object.assign({}, result);
this.chartData = {...result};
Nothing is working, any help would be appreciated :)
this.chartData = Object.assign({}, result);
this.chartData = {...result};
this doesn't clone the whole object, it only changes the top-root object, so for example if you have an object like this
var car = {
model :"bmw",
wheel:{
type:"rounded",
color:"black"
}
}
and you use assign
let anotherCar = {...car} //or Object.assign it's almost same)
the car object will be new, but the wheel object will be the same, and car and anotherCar will reference to the same object, sou you have to make deep clone, the easiest way right now is using JSON methods
var newCar = JSON.parse(JSON.stringify(car)); // it will create whole new object
A quick note about Object.assign()
and {...obj}
object copying: both of them make a shallow copy of an object meaning that only own top-level properties will be copied.
An example:
const obj = {a: 5};
const withNested = {b: 4, nested: obj};
const copy = {...withNested};
copy.nested === withNested.nested // outputs 'true' meaning the objects are the same and have not been copied
The code above shows that nested objects will not be cloned . To make your code work correctly make a deep clone manually: {...a, b: {...source.b}}
or use lodash
's _.cloneDeep(source)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.