skip to Main Content

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


  1. Chosen as BEST ANSWER

    The code mentioned in the below link by Nick Grealy worked for me.

    Accessing nested JavaScript objects and arrays by string path

    const deep_value = (obj, path) => 
    path
        .replace(/[|].?/g, '.')
        .split('.')
        .filter(s => s)
        .reduce((acc, val) => acc && acc[val], obj);
    
    
    console.log(deep_value(someObject, "part1.name"));               
    console.log(deep_value(someObject, "pa[rt3[0].name")); 


  2. You can do with a recursive function to navigate through the nested structure

    getValueByFieldName(obj: any, fieldName: string): any {
        const keys = fieldName.split('.');
        let value = obj;
    
        for (const key of keys) {
          if (Array.isArray(value) && /^d+$/.test(key)) {
            // If the current key is a number, treat it as an index for an array
            const index = parseInt(key, 10);
            value = value[index];
          } else {
            value = value[key];
          }
    
          // In case property is undefined
          if (value === undefined) {
            break;
          }
        }
    
        return value;
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search