Skip to content Skip to sidebar Skip to footer

Jquery Pushing Array To Array Item Child Not Working

I am making an app to track goals & the habits that those goals consist of. I am however having trouble pushing the habits array to a specific goal. I can declare the array of

Solution 1:

You're looping over the array itself, but children is also an array

for (var i = 0; i < _priValues.length; i++) { 
  var item = `
    <h6>${_priValues[i].name}</h6>     
    <ul class="collectionDetails">                                        
      ${_priValues[i].children.map(child => "<li>" + child + "</li>"}                           
    </ul>`; 
  $('.priorityList ul.collection').append(item); 
};

The above uses .map to turn the children array to a list of li.


Also that doing this:

_priValues.push({
        [id] : {
            name : "maingoal",
            children : "subgoal"
        }
    });

redefines children as a simple string (Welcome to Javascript, where you can change types at runtime!). What you probably meant to do there is:

_priValues.push({
        [id] : {
            name : "maingoal",
            children : ["subgoal"]
        }
    }); 

Note the addition of [ & ] keeping children as an array with 1 element.


Here is an example of your code working as (I think) you expect:

var _priValues = [{
  name:"Foo",
  children:["bar"]
}];


functionredraw(){
  $('.priorityList').empty();
  for (var i = 0; i < _priValues.length; i++) { 
    var item = `
      <h6>${_priValues[i].name}</h6>     
      <ul class="collectionDetails">                                        
        ${_priValues[i].children.map(child => "<li>" + child + "</li>")} 
      </ul>`; 
    $('.priorityList').append(item); 
  };
}
redraw();

$('.addItem').on("click",() => {
   _priValues.push({
      name:"new-item", children:["item1"]
   });
   redraw();
})

$('.addChild').on("click",() => {
   _priValues[0].children.push("new-item");
   redraw();
})
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><divclass="priorityList"></div><buttonclass="addItem">Add new top level item</button><buttonclass="addChild">Add a new child to the first item</button>

Post a Comment for "Jquery Pushing Array To Array Item Child Not Working"