简体   繁体   中英

JQuery push array to specific element in array

I'm making a webapp with the help of JQuery to keep track of goals & habits. One can add a main goal such as 'Discipline', and then afterwards can attach subgoals or habits to said main goal (eg 'work out everyday').

Organizing the array for main goals is obvious;

goals = ['Acceptance', 'Discipline', 'Accountability'];

I however have found no way in JQuery/Javascript to attach/add an array of items to a specific item in ANOTHER array.

Is there an easier way to do this, with JSON for example?

Thanks in advance for any help offered

You do this by storing an array of objects at the top level, with a property for the child array

var goals  = [{
  name: "Acceptance",
  children:[]
},{
  name: "Discipline",
  children:[]
},{
  name: "Accountability",
  children:[]
}];

When it comes to adding your child you just push it to the child array

goals[0].children.push("Work out every day");

Another option is store key/values at the top level

var goals = {"Acceptance":[],"Discipline":[],"Accountability":[]};

Slightly less versatile, but adding an item to a specific element slightly easier

goals["Acceptance"].push("Work out every day");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM