I am working on nested array and try to find a value inside the nested array based on condition. The API returns the data in the format shown below.
data=
{
"ch_Id": "1234",
"title": "Title",
"status": 4,
"options": [
{
"ch_message": "ABC broad casting ",
"ch_title": "ABC",
"referenceType": "Internal"
}
],
"stage": "active"
}
]
I am working on loading data dynamically into a div based on a condition. So based on a condition, sometimes the fieldname is ch-Id, and other times it is options[0].ch_message. So, how do I dynamically retrieve the value of fieldname whatever is coming from the input and bind it to the div?
For ch_Id, I can get the value using data[ch_Id], but if I give data[options[0].ch_message], I get undefined.
displayValue: any;
constructor() { }
ngOnInit(): void {
this.fieldName= resultData[fieldName] ;// this can be ch_Id or options[0].ch_message
// Filter the array value based on fieldName
const filteredData = Object.entries(this.data).filter(([key, value]) => key === this.fieldName)
this.displayValue = filteredData[0][1]
console.log('this.displayValue',this.displayValue);
}
2
Answers
The code mentioned in the below link by Nick Grealy worked for me.
Accessing nested JavaScript objects and arrays by string path
You can do with a recursive function to navigate through the nested structure