Search code examples
arraysjsonjson2html

Conditional selecting from a JSON array


I'm trying to select and display specific JSON data within an array. The data looks like this:

{ "thingys" : [
  {
    "type" : "thingy1",
    "text" : "this is thingy1"
  },
  {
    "type" : "thingy2",
    "text" : "this is thingy2"
  },
  {
    "type" : "thingy3",
    "text" : "this is thingy3"
  }
]}

I'm using json2html, and I would normally use something like

{"tag":"div","html":"${thingys.text}"}

This would be fine, but I want to be able to specify that I want ${thingys.text} where ${thingys.type} == "thingy3". How would I go about doing this?


Solution

  • best way to achieve something like this would be to include an inline function to process the the "thingys" Something like this

    var transforms = {
    'main': {"tag":"div","children":function() {
    
      var out = [];
      for(var i=0; i < this.thingys.length; i++)
         if(this.thingys[i].test == "thingy3") out.push(this.things[i]);
    
      return( json2html.transform(out,transforms.thing) );
    }},
    
    'thing':{"tag":"div","html":"${text}"}
    };