0

I have the json data below and need to create a function to get all child elements based on a given parent element (Item 1-3):

{
  "temps": {
    "Item1": [
      {
        "time": 123,
        "value": 155
      },
      {
        "time": 123,
        "value": 185
      }
    ],
    "Item2": [
      {
        "time": 123,
        "value": 189
      },
      {
        "time": 123,
        "value": 192
      }
    ],
    "Item3": [
      {
        "time": 123,
        "value": 184
      }
    ]
    ]
  }
}

What i already have is this each function:

$.each(data.temps,function(index, object){
// get parent items
console.log(index +'('+object.length+')')

 $.each(object, function(idx, sensor) {
 // get all childs
 console.log(sensor);
});
});
VillageTech
  • 1,968
  • 8
  • 18
Marco
  • 131
  • 1
  • 9
  • 1
    JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Dec 11 '19 at 07:44
  • 1
    It's not clear what result you want...? – T.J. Crowder Dec 11 '19 at 07:45
  • Sorry it is not clear for me why that is not json? What i want is (of course read json in JS) a foreach to get all childs from parent item. For example if set "item2" as reference i want the child elements : {time: 123, value: 189} {time: 123, value: 192} – Marco Dec 11 '19 at 08:15
  • What's shown in the question is valid JSON, but `data` in your code clearly doesn't contain JSON (which would be a **string**), it contains a reference to an object. Read the linked page for details. – T.J. Crowder Dec 11 '19 at 08:17
  • 1
    If your staring point is `targetItem = "Item2"` (for instance), then it's `children = data[targetItem]`, see the [linked question](http://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable)'s answers for details. – T.J. Crowder Dec 11 '19 at 08:19
  • 1
    `function get_items(ref){ for(var k in json_string["temps"][ref]) { console.log(k); } }` – temo Dec 11 '19 at 08:28
  • Thanks, that anserd my question! – Marco Dec 11 '19 at 08:28

0 Answers0