azharmalik3
azharmalik3

Reputation: 563

Getting error while getting specified index object

I want to get first index object from list of objects. Here is sample object:

[%VendorModel{__meta__: #Ecto.Schema.Metadata<:loaded>,
  cameras: #Ecto.Association.NotLoaded<association :cameras is not loaded>,
  config: %{"auth" => %{"basic" => %{"password" => "12345",
        "username" => "admin"}},
    "snapshots" => %{"h264" => "h264/ch1/main/av_stream",
      "jpg" => "Streaming/Channels/1/picture"}}, exid: "ds-2cd2032-i", id: 332,
  name: "DS-2CD2032-I",
  vendor: #Ecto.Association.NotLoaded<association :vendor is not loaded>,
  vendor_id: 6},
 %VendorModel{__meta__: #Ecto.Schema.Metadata<:loaded>,
  cameras: #Ecto.Association.NotLoaded<association :cameras is not loaded>,
  config: %{"auth" => %{"basic" => %{"password" => "12345",
        "username" => "admin"}},
    "snapshots" => %{"h264" => "h264/ch1/main/av_stream",
      "jpg" => "Streaming/Channels/1/picture", "mjpg" => "/",
      "mpeg4" => "mpeg4/ch1/main/av_stream"}}, exid: "ds-2cd2612f-i", id: 2911,
  name: "DS-2CD2612F-I",
  vendor: #Ecto.Association.NotLoaded<association :vendor is not loaded>,
  vendor_id: 6},
 %VendorModel{__meta__: #Ecto.Schema.Metadata<:loaded>,
  cameras: #Ecto.Association.NotLoaded<association :cameras is not loaded>,
  config: %{"auth" => %{"basic" => %{"password" => "mehcam",
        "username" => "admin"}},
    "snapshots" => %{"h264" => "h264/ch1/main/av_stream",
      "jpg" => "Streaming/Channels/1/picture", "mjpg" => "/",
      "mpeg4" => "mpeg4/ch1/main/av_stream"}}, exid: "ds-2df5274-a", id: 2913,
  name: "DS-2DF5274-A",
  vendor: #Ecto.Association.NotLoaded<association :vendor is not loaded>,
  vendor_id: 6}]

I want to get specified index object. like:

%VendorModel{__meta__: #Ecto.Schema.Metadata<:loaded>,
  cameras: #Ecto.Association.NotLoaded<association :cameras is not loaded>,
  config: %{"auth" => %{"basic" => %{"password" => "12345",
        "username" => "admin"}},
    "snapshots" => %{"h264" => "h264/ch1/main/av_stream",
      "jpg" => "Streaming/Channels/1/picture"}}, exid: "ds-2cd2032-i", id: 332,
  name: "DS-2CD2032-I",
  vendor: #Ecto.Association.NotLoaded<association :vendor is not loaded>,
  vendor_id: 6}

I am trying to get object using objects[0] but it gave following error message. Error: ** (ArgumentError) the Access calls for keywords expect the key to be an atom, got: 0.

Please help me to solve this issue.

Upvotes: 4

Views: 5717

Answers (1)

Gazler
Gazler

Reputation: 84140

You have a few options for getting an element from the list.

If you want the first item (index 0) you can do:

[item | _tail] = items

The entry at the head of the list will be bound to item.

You can also use the hd/1 function which can be useful in a pipeline:

item = hd(items)

If you want a specific index from the list you can use Enum.at/3:

item = Enum.at(items, 5)

Upvotes: 9

Related Questions