Modifying the response array objects

I want to get just the id and name from the object the rest of the data are irrelevant to me.
Can you pleas help me how to go about that.

def call(param) do
    System.get_env("LOCATION_SERVICE_HOST") <> param
      |> HttpClient.get
      |> format_response
end

def format_response({ok, response}) do
    response
 end

The response of call function

[
    {
        "countryCode": "IN",
        "courierApplicable": false,
        "id": 1,
        "isActive": true,
        "name": "",
        "stateId": 5,
        "supplierCityId": 1
    },
    {
        "countryCode": "IN",
        "courierApplicable": false,
        "id": 2,
        "isActive": true,
        "name": "",
        "stateId": 1,
    },
  ...
]

Expected result

[
    {
        "id": 1,
        "name": ""
    },
    {
        "id": 2,
        "name": ""
    },
  ...
]

What have you tried so far?

I don’t know where to start

I tried this but obviously it failed

 def format_response({ok, response}) do
    response
      |> Enum.flat_map(fn params -> show(params) end)
 end

  def show(%{"id" => id, "name" => name}) do
    %{
      id: id,
      name: name
    }
  end

When it fails, You should always include error messages.

Also, it looks like a list of map, but You use it with tuple syntax.

Why Enum.flat_map? Enum.map should do the trick as well.

|> Enum.map(fn x -> %{id: x.id, name: x.name} end)

This seems to have worked

1 Like

This would have worked too

|> Enum.map(& %{id: &1.id, name: &1.name})

BTW “id” is not equal to id:, but the working code uses :id…