0

I've been working on a layout library. it is broken up into panels object. I need to search the nested elements for an id and insert data before or after the target element. I can use splice to place the new element but what I can't work out how is search the obj. If posible I would prefer not to use an external library.

any advice or help with this would be very much appreciated

here is an example of a panel object

panel['menu'] = 
{
"id":"menu",
"css":"panel",
"floating":true,
"elements":[{
           "id":"menu-header",
           "html":"<h1 class=\"header\">Loading</h1>",
           "index":0,
           "sib_count":1
           }]
};
Pointy
  • 405,095
  • 59
  • 585
  • 614
ianmac
  • 39
  • 5
  • 1
    You search for the object by iterating over the array. – Felix Kling Oct 13 '11 at 21:49
  • possible duplicate of [Find object by id in array of javascript objects](http://stackoverflow.com/questions/7364150/find-object-by-id-in-array-of-javascript-objects) – Felix Kling Oct 13 '11 at 21:50
  • Will everything be in the elements array? or can there be elements nested within the elements array? Is it only one level deep or is it possible to be 5, 10, 50 levels deep? Can they exist outside of the elements array. – jyore Oct 13 '11 at 22:13

1 Answers1

0

You can just iterate through the array and look for the id you want

var elements = panel['menu']['elements'];
for ( var i = 0; i < elements.length; i++ ) {
    if ( elements[i]['id'] === "some id" ) {
        elements.splice( i, 0, /* new elements */ );
    }
}
Will
  • 19,661
  • 7
  • 47
  • 48