ViniciusCR
ViniciusCR

Reputation: 131

How update/transform values from objects inside an array in Dart

Given an array of objects, iterate over it and change/add a few props while keeping most of the original props intact.

in javascript it would look like:

const trips = [
    { status: 1, name: "trip1", foo: "bar" }, 
    { status: 1, name: "trip2", foo: "bar" }, 
    { status: 3, name: "trip3", foo: "foobar" }]

const formatedTrips = trips.map(trip => ({
    ...trip,
    status: 1,
    foo: trip.foo === "bar" ? ` ${trips.name} bar` : "barbar"
}))

/**
 *  formatedTrips = [
        { status: 1, name: "trip1", foo: "trip1 bar" }, 
        { status: 1, name: "trip2", foo: "trip2 bar" }, 
        { status: 1, name: "trip3", foo: "barbar" }
    ]
 */

Upvotes: 0

Views: 774

Answers (1)

Tomer Ariel
Tomer Ariel

Reputation: 1537

dart has all of the standard array methods such as map, filter (it's called where), reduce and so on. They are very intuitive and feel very similar to JS. docs

More specifically, it depends on the type of trip. Is it a map? An instance of a custom class? If you'll share the inner workings of your code it'll be easier to help.

Upvotes: 2

Related Questions