Write a code to pupulate nesting list array object data on UI in JS | JS, TS, React and Angular Forum
J
JYOTI SHARMA Posted on 04/01/2022


var structure = {
name: 'alpha',
array: [{
name: 'beta',
object: {
name: 'alpha1',
array: [{
name: 'beta1'
}, {
name: 'gamma1'
}],
object: {
name: 'delta1',
array: [{
name: 'epsilon1'
}]
}
}
}, {
name: 'gamma'
}],
object: {
name: 'delta',
array: [{
name: 'epsilon'
}]
}
};


Y
Yogesh Chawla Replied on 04/01/2022

Remember we discussed that we can use bracket notation to access multi word property in Object. We do that because space is not a valid character in identifier names.

Example:

let user = { "address with zip code" : "ABC" };
const value = user["address with zip code"];
console.log(value);

Similarly array elements are also accessed using bracket notation:

const value = arr[5]; // arr.5 would be a syntax error

Now how to access nested data structures:
A nested data structure is an array or object which refers to other arrays or objects.
Such structures can only be accessed by consecutively applying dot or bracket notation.

Example:

const data = {
    code: 42,
    items: [{
        id: 1,
        name: 'ABC'
    }, {
        id: 2,
        name: 'XYZ'
    }]
};


To access the name of the second item. Here is how we do it step-by-step:

As we can see data is an object hence we can access its properties using dot notation. The items property is accessed as follows:

data.items

The value is an array, to access its second element, we have to use bracket notation:

data.items[1]

This value is an object and we use dot notation again to access the name property. So we eventually get:

const item_name = data.items[1].name;

Alternatively, we can use bracket notation also for any of the properties:

const item_name = data['items'][1]['name'];

 

NOW COMING TO YOUR CODE. DO THIS TO ACCESS INDIVIDUAL ELEMENT or NESTED ELEMENTS:

var structure = {
  name: 'alpha',
  array: [{
    name: 'beta',
    object: {
      name: 'alpha1',
      array: [{
        name: 'beta1'
      }, {
        name: 'gamma1'
      }],
      object: {
        name: 'delta1',
        array: [{
          name: 'epsilon1'
        }]
      }
    }
  }, {
    name: 'gamma'
  }],
  object: {
    name: 'delta',
    array: [{
      name: 'epsilon'
    }]
  }
};

const item_name = structure.array[0].name;
console.log(item_name);

function toArray(structure) {
    const result = [];
    for (const prop in structure) {
        const value = structure[prop];
        if (typeof value === 'object') {
            result.push(toArray(value)); // <- recursive call
        }
        else {
            result.push(value);
        }
    }
    return result;
}

console.log(toArray(structure));