skip to Main Content

i have a json.

{
    "result": [
        {
            "id": 2,
            "e_id": 2,
            "e_name": "0",
            "abc": 0,
            "doa": "2021-02-15 13:17:11"
        },
        {
            "id": 3,
            "e_id": 22,
            "e_name": "ok",
            "abc": 1,
            "doa": "2021-02-15 13:17:57"
        }
    ],
    "status": 1,
    "msg": "Successfully fetched"
}

and list

[2,1,5]

i want to add another key to the json where there is matched from the list array

{
    "result": [
        {
            "id": 2,
            "e_id": 2,
            "e_name": "0",
            "abc": 0,
            "doa": "2021-02-15 13:17:11",
            "added_key": "added value because the id number 2 is matched from the list array"
        },
        {
            "id": 3,
            "e_id": 22,
            "e_name": "ok",
            "abc": 1,
            "doa": "2021-02-15 13:17:57"
        }
    ],
    "status": 1,
    "msg": "Successfully fetched"
}

here is what i have tried

List list = [2,1,5];
      for (var i = 0;i < list.length; i++) {
        int aa = data.indexWhere((item) => item["id"] == list[i]);
        data[aa]["added_key"] = "added value";
 }

anyone who have any idea how to do that using dart? please share your code.

2

Answers


  1. Hey I think you need to run loop of the data you are getting. So, it’s easy for you to keep track.
    What about trying below solution.

     data["result"] = data["result"].map((item) {
        final id = item["id"] as int; // Ensure type safety
        if (matchList.contains(id)) {
             // Add the new key with a relevant value
             item["added_key"] = "added value (ID: $id)";
         }
         return item;
      }).toList();
    
    Login or Signup to reply.
  2. I think I would turn it around and iterate through the results and check if the list contains the id. If the list is long, you could turn it into a set, because a contains lookup of a (HashSet would be faster than in a List)

    for(final entry in data["result"]) {
        if (list.contains(entry['id'])) {
            entry['added_key'] = 'added value';
        }
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search