简体   繁体   中英

Problem with ordering headings in a sorted list

I am building a web application in which I build a sorted list out of an object like this:
{head: {subhead: [list_items], subhead: [list_items]}, head: {subhead: [list_items]}} .
My problem is that I have to ensure the headings and subheading always follow in a certain order. This is complicated by the fact that headings and subheadings that may be added later on also need to follow this order. So the only way I could think to inform the parser of the order would be to give it some data like this:
{heads: [head1, head2, head3], subheads: {head1: [subhead1_1, subhead1_2], head2: [subhead2_1, subhead2_2, subhead2_3]}} ,
but that strikes me as overly verbose and repeating data that would be in the original data structure.

You might as well use an array (or your own structure) for this since you want it to be ordered. Your own structure might look like:

function Head(name) {
  this.name = name;
  this.arr = [];
}

So instead of the structure:

var thing = {
  food: {fruit: [apples, oranges], vegetables: [carrots, peas]},
  animals: {domestic: [cat, dog], wild: [lion, bear]}
}

You might do:

var thing = [new Head('food'), new Head('animals')]

Then:

thing[0].arr.push('apples'); 
thing[0].arr.push('oranges');

etc.

Of course you don't have to make a class, since you can actually attach properties to arrays in javascript. But making the datastructure would be a bit more of a pain.

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