1
votes

newbie here. would anyone know how can i match the value of list x to the value of list y's key["id"]?

thank you in advance! appreciate any help. =)

list x = ["open_box", "close_box"];
list y = 
[
    {
        "id": "open_box",
        "name": "Open",
        "action": ["open_box"]
    },
    {
        "id": "close_box",
        "name": "Close",
        "action": ["open_box", "close_box", "pull_box"]
    },
    {
        "id": "pull_box",
        "name": "Pull",
        "action": ["open_box", "close_box", "pull_box", "push_box"]
    }
]
3

3 Answers

1
votes

loop through x using for in, and then finally you can use where method from List

for (String action in x) {
  dynamic temp = y.where((data) => data['id'] == action);
  if (temp.isNotEmpty) {
    // do someting
    print(temp);
  }
}

Ref: Dart Documentation - List

1
votes

List provides a where method that allows you to filter the list based on a condition. Here I am using the where method of the y list and searching the x list for the id value of the current item in the y list. I check the length of the search for the x list and if it is greater than zero, then we have found a match inside the x list for that id. z will hold the list of items that have matched the ids from the x list inside the y list.

List x = ["open_box", "close_box"];
List y = 
[
        {
                "id": "open_box",
                "name": "Open",
                "action": ["open_box"]
        },
        {
                "id": "close_box",
                "name": "Close",
                "action": ["open_box", "close_box", "pull_box"]
        },
        {
                "id": "pull_box",
                "name": "Pull",
                "action": ["open_box", "close_box", "pull_box", "push_box"]
        }
];
var z = y.where((data) => x.where((value) => value==data["id"]).length>0);
print(z);

Here is the expected output

I/flutter ( 6086): ({id: open_box, name: Open, action: [open_box]}, {id: close_box, name: Close, action: [open_box, close_box, pull_box]})
1
votes
    list x = ["open_box", "close_box"];
    list y = 
    [
        {
            "id": "open_box",
            "name": "Open",
            "action": ["open_box"]
        },
        {
            "id": "close_box",
            "name": "Close",
            "action": ["open_box", "close_box", "pull_box"]
        },
        {
            "id": "pull_box",
            "name": "Pull",
            "action": ["open_box", "close_box", "pull_box", "push_box"]
        }
    ];
    var i,j;
    var yy=jsonDecode(y);
for(j=0;j<=x.length;j++){
    for(i=0;i<=yy.length;i++){

    if(yy[i]['id'].contains(x[j])){
    
    //Do something if true
    print(yy[i]);
    
    }
    }
}

This code compare x[0] means "open_box" to all List of Maped data of y it will print index value where conditions true