What is the equivalent of Object.assign in Dart?

Viewed 1118

in javascript whe have Object.assign and we can use them like this:

var a = {name:'car', value: 2}
var b = {name:'car', value: 65, speed: 100}
var c = {name:'car', value: 5}
var result = {}
Object.assign(result, a)
Object.assign(result, b)
Object.assign(result, c)
// result == {name: "car", value: 5, speed: 100}

how i can make that in dart?

1 Answers

What you are doing in JavaScript is treating objects as maps. You can do the same thing in Dart if you use maps.

var a = {'name': 'car', 'value': 2}
var b = {'name':'car', 'value': 65, 'speed': 100}
var c = {'name':'car', 'value': 5}
var result = {}
result.addAll(a);
result.addAll(b);
result.addAll(c);
print(result); // {"name": "car", "value": 5, "speed": 100}

If you want to do something similar for Dart objects, you'll have to use reflection (dart:mirrors) which isn't available on all platforms, and you have to code it yourself, there is no general function doing what you want (assigning variables based on Map data).

Related