skip to Main Content

I have a nested object where the inner objects have random serial numbers as their labels.

If I have data like this:

const user = {
    id: 101,
    email: '[email protected]',
    personalInfo: {
        name: 'Jack',
        address: {
            line1: 'westwish st',
            line2: 'washmasher',
            city: 'wallas',
            state: 'WX'
        }
    }
}

I can access the inner object with

const name = user.personalInfo.name;
const userCity = user.personalInfo.address.city;

But my inner objects have random serial numbers, not static labels like address as in the above example.

{
    "id": "48121be5c6b55ae23928316f5",
    "component": "select",
    "customFields": [

    ],
    "index": 0,
    "label": "Select",
    "description": null,
    "placeholder": null,
    "editable": true,
    "options": {
      "f1c7363b085cd671a59": {
        "index": 0,
        "value": "AA",
        "label": "A"
      },
      "3d8508fb86c6af84637": {
        "index": 1,
        "value": "BB",
        "label": "B"
      },
      "615b8ba2c0b7e88b8b5": {
        "index": 2,
        "value": "DD",
        "label": "D"
      }
    },
    "required": false,
    "validation": "/.*/",
    "imported": false
  }

How do I access the value for each inner object of the options object?

3

Answers


  1. If they are a constant length, you can try using a RegExp pattern to match the string

    
    const serialRegex = new RegExp('^[a-z0-9]{19}$')
    const serial = options[serialRegex].value
    
    Login or Signup to reply.
  2. To access the inner objects’ data within the "options" object,
    you can use Object.keys() and for…of method to iterate through the keys and access their respective data.

    please check below code example:

      const productDetails = {
      "id": "48121be5c6b55ae23928316f5",
      "products": {
        "b14ea0b7ed094618a341424a": {
          "index": 0,
          "value": "AA",
          "label": "A"
        },
        "3958b0085dcf4bde9e0bf8f15": {
          "index": 1,
          "value": "BB",
          "label": "B"
        },
        "6b38bd4df2aa438caf0e85b7": {
          "index": 2,
          "value": "DD",
          "label": "D"
        },
        //...more objects
      }
    };
    
    const productKeys = Object.keys(productDetails.products);
    
    for (const key of productKeys) {
      const innerObject = productDetails.products[key];
      console.log(`Key: ${key}`);
      console.log(`Value: ${innerObject.value}`);
    }
    Login or Signup to reply.
  3. You can use Object.keys() to iterate through the properties of the "options" object like this:

    const optionKeys = Object.keys(data.options);
    optionKeys.forEach(key => {
        const innerObject = data.options[key];
        console.log(innerObject.value); // Access the "value" property of each inner object
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search