Home > Software engineering >  Adding elements from one array to another array
Adding elements from one array to another array

Time:08-04

I have a list of data array from an API and I need to check the id with another hardcoded data array id.And I need to add two data elements which I'm getting from the api data array to the hardcoded array.

This is the hardcoded data array.

List<Data> data = [
  Data(id: 1, title: 'title 1', comment: null, selected: null),
  Data(id: 2, title: 'title 2', comment: null, selected: null),
  Data(id: 3, title: 'title 3', val: null, comment: null, selected: null),
];

This is the data response from the API.

"data": [
        {
            "id": 1,
            "value": "value 1",
            "comment": "comment 1",
            "userId": 1,
        
        },
    {
            "id": 2,
            "value": "value 2",
            "comment": "comment 2",
            "userId": 2,
        
        },
    {
            "id": 3,
            "value": "value 3",
            "comment": "comment 3",
            "userId": 3,
        
        },
]

What I wanna do is the value I'm getting for comment and value from this response data list to add to the hardcoded array comment and selected.They're initially null.

CodePudding user response:

Consider a dynamic list

  List<dynamic> data = [
    { 'id': 1, 'title': 'title 1', 'comment': null, 'selected': null },
    { 'id': 2, 'title': 'title 2', 'comment': null, 'selected': null },
    { 'id': 3, 'title': 'title 3', 'val': null, 'comment': null, 'selected': null},
  ];

and the response from api is

List<dynamic> apiResp = [
    {
      "id": 1,
      "value": "value 1",
      "comment": "comment 1",
      "userId": 1,
    },
    {
      "id": 2,
      "value": "value 2",
      "comment": "comment 2",
      "userId": 2,
    },
    {
      "id": 3,
      "value": "value 3",
      "comment": "comment 3",
      "userId": 3,
    },
  ];

to update the comment and selected fields from api response you can do something like this

  for (var each in data) {
     var index = apiResp.indexWhere((element) => element!['id']!.toString() == each!['id']!.toString());
     if (index > -1) {
       data[index]!['comment'] = apiResp[index]!['comment'];
       data[index]!['selected'] = apiResp[index]!['selected'];
     }
  }

if you want to make sure your data is updated just print it like this

  // print to ensure the data is update
  for (var each in data) {
    print(each);
  }

Note: I added .toString with id incase if you are not sure about data type and also if your response from api is not in list form you can convert it,

 var data = json.decode(utf8.decode(response.bodyBytes));
 return data.toList();
  • Related