-1

I want to be able to parse this json tree and get the value of the attribute checked for every element :

{
    "children": [
        {
            "children": [
                {
                    "children": [],
                    "id": 49,
                    "name": "nice",
                    "checked": true,
                    "level": 3,
                    "path": "0_1_0_0",
                    "lineLength": 180
                }
            ],
            "id": 48,
            "name": "amira",
            "checked": false,
            "level": 2,
            "path": "0_1_0"
        }
    ],
    "id": 47,
    "name": "mahdi",
    "checked": true,
    "level": 1,
    "path": "0_1"
}


I'm able to read the data this way :

var data = this.flatData;


I want to be able to read the checked attribute for every child inside a for loop or a foreach and if it's true set a certain behaviour to my code do any one know how to do this and thanks in advance.

xianshenglu
  • 4,943
  • 3
  • 17
  • 34
  • 1
    Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available static and instance methods of [`Object`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Nov 26 '21 at 14:14
  • Which part are you having difficulty with? It's unclear if you've converted the JSON *string* to an object, but you do say you've parsed it. Are you asking how to generate a [for loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration)? Or is it because your `children` property needs recursion? – freedomn-m Nov 26 '21 at 14:15

1 Answers1

0

You can use a recursion; in your particular structure something like:

const func = (elem) => {
  if (elem.children) elem.children.forEach((elem) => func(elem));
  if (elem.checked) console.log(`act on elem with id: ${elem.id}`);
}
func(test);
Juergen Riemer
  • 1,393
  • 2
  • 13
  • 29