This is my data map list
data =
[
{
"group": "A",
"direction": "N",
"city": [
{
"city": "CITY1",
"code": "001",
"subCity": [
{
"subCityCode": "C1001",
"member": "15"
},
{
"subCityCode": "C1002",
"member": "20"
}
]
},
{
"city": "CITY2",
"code": "002",
"subCity": [
{
"subCityCode": "C2001",
"member": "42"
},
{
"subCityCode": "C2002",
"member": "65"
}
]
},
]
},
{
"group": "B",
"direction": "S",
"city": [
{
"city": "CITY1",
"code": "001",
"subCity": [
{
"subCityCode": "C1001",
"member": "21"
}
{
"subCityCode": "C1002",
"member": "47"
}
]
},
{
"city": "CITY2",
"code": "002",
"subCity": [
{
"subCityCode": "C2001",
"member": "65"
}
{
"subCityCode": "C2002",
"member": "17"
}
]
},
]
},
]
I would like to change "member": "100" of "subCityCode": "C1001" of "city": "CITY1" of "group": "A"
Therefore I write code like this
data[0]['city'][0]['subCity'][0]['member'] = 100;
And the result is
data =
[
{
"group": "A",
"direction": "N",
"city": [
{
"city": "CITY1",
"code": "001",
"subCity": [
{
"subCityCode": "C1001",
"member": "100"
},
{
"subCityCode": "C1002",
"member": "20"
}
]
},
{
"city": "CITY2",
"code": "002",
"subCity": [
{
"subCityCode": "C2001",
"member": "42"
},
{
"subCityCode": "C2002",
"member": "65"
}
]
},
]
},
{
"group": "B",
"direction": "S",
"city": [
{
"city": "CITY1",
"code": "001",
"subCity": [
{
"subCityCode": "C1001",
"member": "100"
}
{
"subCityCode": "C1002",
"member": "47"
}
]
},
{
"city": "CITY2",
"code": "002",
"subCity": [
{
"subCityCode": "C2001",
"member": "65"
}
{
"subCityCode": "C2002",
"member": "17"
}
]
},
]
},
]
why the data at index 1 also change it
Why data[1] at ['city'][0] at ['subCity'][0] at ['member'] = 100
and how to change only data[0]
--Thank you--
CodePudding user response:
I suppose you have added this data by code, and since dart works on refrences the 2nd object has the same refrence as the first one (as i can see the values are the same)
You can try jsonDecode jsonEncode on object before adding to map.
I have tried the same code and it works fine
void main() {
var data =
[
{
"group": "A",
"direction": "N",
"city": [
{
"city": "CITY1",
"code": "001",
"subCity": [
{
"subCityCode": "C1001",
"member": "15"
},
{
"subCityCode": "C1002",
"member": "20"
}
]
},
{
"city": "CITY2",
"code": "002",
"subCity": [
{
"subCityCode": "C2001",
"member": "42"
},
{
"subCityCode": "C2002",
"member": "65"
}
]
},
]
},
{
"group": "B",
"direction": "S",
"city": [
{
"city": "CITY1",
"code": "001",
"subCity": [
{
"subCityCode": "C1001",
"member": "21"
},
{
"subCityCode": "C1002",
"member": "47"
}
]
},
{
"city": "CITY2",
"code": "002",
"subCity": [
{
"subCityCode": "C2001",
"member": "65"
},
{
"subCityCode": "C2002",
"member": "17"
}
]
},
]
},
];
(data[0]['city'] as List)[0]['subCity'][0]['member'] = "100";
print("NEW DATA --- ${data}");
}