0

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" }
    ]
 */

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I've checked most of array method, but didn't find any that does this simple transformations. trip is just an object that was mapped from a api response. But I've updated the code to give more details about it'
Are you somewhat familiar with dart's type system? dart is a statically typed language with no concept of native key: value objects like JS objects. Instead, there are different types such as Map<String, dynamic> which are probably more suited to what you need. Something like var a = {"wouldCompile": false} just isn't valid dart code. Again - if you were to share some of the dart source code, it would be much easier to help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.