Skip to content

Instantly share code, notes, and snippets.

@kumar-aakash86
Last active September 30, 2021 15:12
Show Gist options
  • Save kumar-aakash86/a7f4a869d02db3b929e3814db28fcbe1 to your computer and use it in GitHub Desktop.
Save kumar-aakash86/a7f4a869d02db3b929e3814db28fcbe1 to your computer and use it in GitHub Desktop.
Updating child array as per parent
var json = {
"Accessories": [
{
"id": 1,
"brand": "samsung",
"parentId": null,
"children": [
{"id": 4, "name": "Ace", "parentId": 1},
{"id": 5, "name": "note", "parentId": 1},
{"id": 6, "name": "galaxy", "parentId": 1}
]
},
{
"id": 2,
"name": "Asus",
"parentId": null,
"children": [
{"id": 7, "name": "gaming", "parentId": 2},
{"id": 8, "name": "office", "parentId": 2}
]
},
]
};
void main() {
var list = Accessories.fromMap(json);
list.accessories?.forEach((e) {
var brand = e.brand;
if (brand != null) {
e.children?.forEach((element) {
element.brand = brand;
});
}
});
print(list.toMap().toString());
}
class Accessories {
Accessories({
this.accessories,
});
List<Accessory>? accessories;
factory Accessories.fromMap(Map<String, dynamic> json) => Accessories(
accessories: json["Accessories"] == null
? null
: List<Accessory>.from(
json["Accessories"].map((x) => Accessory.fromMap(x))),
);
Map<String, dynamic> toMap() => {
"Accessories": accessories == null
? null
: List<dynamic>.from(accessories!.map((x) => x.toMap())),
};
}
class Accessory {
Accessory({
this.id,
this.brand,
this.parentId,
this.children,
this.name,
});
int? id;
String? brand;
String? parentId;
List<Child>? children;
String? name;
factory Accessory.fromMap(Map<String, dynamic> json) => Accessory(
id: json["id"],
brand: json["brand"],
parentId: json["parentId"],
children: json["children"] == null
? null
: List<Child>.from(json["children"].map((x) => Child.fromMap(x))),
name: json["name"],
);
Map<String, dynamic> toMap() => {
"id": id,
"brand": brand,
"parentId": parentId,
"children": children == null
? null
: List<dynamic>.from(children!.map((x) => x.toMap())),
"name": name,
};
}
class Child {
Child({
this.id,
this.name,
this.brand,
this.parentId,
});
int? id;
String? name;
String? brand;
int? parentId;
factory Child.fromMap(Map<String, dynamic> json) => Child(
id: json["id"],
name: json["name"],
brand: json["brand"],
parentId: json["parentId"],
);
Map<String, dynamic> toMap() => {
"id": id,
"name": name,
"brand": brand,
"parentId": parentId,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment