获取指定索引对象时获取错误

时间:2016-03-29 09:20:27

标签: elixir phoenix-framework

我想从对象列表中获取第一个索引对象。这是示例对象:

[%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}]

我想获取指定的索引对象。像:

%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}

我正在尝试使用objects[0]获取对象,但它提供了以下错误消息。错误:** (ArgumentError) the Access calls for keywords expect the key to be an atom, got: 0

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:7)

您可以从列表中获取元素。

如果你想要第一个项目(索引0),你可以这样做:

[item | _tail] = items

列表头部的条目将绑定到item

您还可以使用在管道中有用的hd/1函数:

item = hd(items)

如果您想要列表中的特定索引,可以使用Enum.at/3

item = Enum.at(items, 5)