object_modifier 1.0.0
object_modifier: ^1.0.0 copied to clipboard
A lightweight Dart library for merging, normalizing, and handling complex JSON structures effortlessly.
A lightweight Dart library for merging, normalizing, and handling complex JSON structures effortlessly.
Features #
- π Merge two JSON Map objects recursively.
- π§© Merge and normalize complex List structures with identifier detection.
- βοΈ Custom NonEncodableObjectNormalizer support for non-standard objects.
- πͺ Smart handling of primitive, list, and map types.
- π‘ Simple and universal API: ObjectModifier.mergeMap() and ObjectModifier.mergeList().
Usage #
import 'package:object_modifier/object_modifier.dart';
void main() {
// Example 1: Merge two simple maps
final a = {'name': 'Alice', 'age': 25};
final b = {'age': 24, 'city': 'Paris'};
final mergedMap = ObjectModifier.mergeMap(a, b);
print('Merged Map: $mergedMap');
// Output: {name: Alice, age: 25, city: Paris}
// Example 2: Merge list of maps with automatic ID detection
final listA = [
{'id': 1, 'name': 'Alice'},
{'id': 2, 'name': 'Bob'},
];
final listB = [
{'id': 1, 'age': 25},
{'id': 3, 'name': 'Charlie'},
];
final mergedList = ObjectModifier.mergeList(listA, listB);
print('Merged List: $mergedList');
// Output (order may vary):
// [
// {id: 1, name: Alice, age: 25},
// {id: 2, name: Bob},
// {id: 3, name: Charlie}
// ]
// Example 3: Use custom normalizer for non-encodable objects
final x = {'created': DateTime(2025, 1, 1)};
final y = {'created': 'old'};
final normalized = ObjectModifier.mergeMap(x, y, (a, b) {
if (a is DateTime) return a.toIso8601String();
return a ?? b;
});
print('Normalized: $normalized');
// Output: {created: 2025-01-01T00:00:00.000}
}
Test #
import 'package:flutter_test/flutter_test.dart';
import 'package:object_modifier/object_modifier.dart';
void main() {
group('ObjectModifier', () {
test('merge two maps', () {
final a = {'name': 'Alice', 'age': 25};
final b = {'age': 24, 'city': 'Paris'};
final merged = ObjectModifier.mergeMap(a, b);
expect(merged, {'name': 'Alice', 'age': 25, 'city': 'Paris'});
});
test('merge list of maps with unique id', () {
final a = [
{'id': 1, 'name': 'Alice'},
{'id': 2, 'name': 'Bob'},
];
final b = [
{'id': 1, 'age': 25},
{'id': 3, 'name': 'Charlie'},
];
final merged = ObjectModifier.mergeList(a, b);
expect(
merged,
unorderedEquals([
{'id': 1, 'name': 'Alice', 'age': 25},
{'id': 2, 'name': 'Bob'},
{'id': 3, 'name': 'Charlie'},
]),
);
});
test('custom normalizer example', () {
final a = {'value': DateTime(2024, 1, 1)};
final b = {'value': '2023-01-01'};
final merged = ObjectModifier.mergeMap(a, b, (a, b) {
if (a is DateTime) return a.toIso8601String();
return a ?? b;
});
expect(merged['value'], '2024-01-01T00:00:00.000');
});
});
}