0

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 (e.g. '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

1 Answer 1

2

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");
Sign up to request clarification or add additional context in comments.

4 Comments

Works like a charm! Thank you very much!!
Would you have an idea as to why the children.push method isn't having any result ? No error, just nothing getting pushed.
@lvb Not from that description no. Make a minimal reproducible example and post a new question. Feel free to link to the new question here and I'll take a look.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.