Home > Back-end >  how can I use sub-array inside of the main array javascript
how can I use sub-array inside of the main array javascript

Time:10-08

I want to use values from "property: []" sub-array inside the "name: id" section but it gives

"Cannot read property 'property' of undefined" error. How can I prevent the error and solve this?

Basically I want to push datas inside the subarray than use it inside the main array how can I do that?

function generateObject(id, Samplelist) {

  Object[id] = {
    name: Object[id].property[0],
    property: []
  };

  Samplelist.forEach((list, i) => {
    Object[id].property.push({
      type: types[order[i]],
      quality: qual[fileToMap],
    });
  });

}

CodePudding user response:

You can not assign something before initializing it. First create the object, populate the property and then use it to assign other properties.

  function generateObject(id, lists) {

  Object[id] = {
    name: undefined, // you can not existact somethng before adding it
    property: []
  };

  Samplelist.forEach((list, i) => {
    Object[id].property.push({
      type: types[order[i]],
      quality: qual[fileToMap],
    });
  });
  
 // after property is assinged value in foreach you can proceed to assign it  
Object[id].name = Object[id].property[0];  

}
  • Related