如何访问作为键值对的对象数组

时间:2019-09-10 10:07:45

标签: javascript

我想在不使用数组索引的情况下访问id'qwsa221',但只能访问并输出所有数组元素,而不是特定元素。

我尝试使用过滤器,但无法弄清楚如何正确使用它。

 let lists = {
      def453ed: [
        {
          id: "qwsa221",
          name: "Mind"
        },
        {
          id: "jwkh245",
          name: "Space"
        }
      ]
    };

3 个答案:

答案 0 :(得分:3)

使用Object.keys()获取对象的所有键,并使用来检查数组元素中的值。符号

let lists = {
  def453ed: [{
      id: "qwsa221",
      name: "Mind"
    },
    {
      id: "jwkh245",
      name: "Space"
    }
  ]
};
Object.keys(lists).forEach(function(e) {
  lists[e].forEach(function(x) {
    if (x.id == 'qwsa221')
      console.log(x)

  })
})

答案 1 :(得分:0)

您可以使用find

这样操作

 let lists = {
  def453ed: [
    {
      id: "qwsa221",
      name: "Mind"
    },
    {
      id: "jwkh245",
      name: "Space"
    }
  ]
};

console.log(
  lists.def453ed // first get the array
  .find(         // find return the first entry where the callback returns true
    el => el.id === "qwsa221"
  )
)

这是您的过滤器的更正版本:

let lists = {def453ed: [{id: "qwsa221",name: "Mind"},{id: "jwkh245",name: "Space"}]};

// what you've done
const badResult = lists.def453ed.filter(id => id === "qwsa221");
/*
here id is the whole object
{
  id: "qwsa221",
  name: "Mind"
}
*/
console.log(badResult)

// the correct way
const goodResult = lists.def453ed.filter(el => el.id === "qwsa221");
console.log(goodResult)

// filter returns an array so you need to actually get the first entry
console.log(goodResult[0])

答案 2 :(得分:0)

  1. 您可以使用Object.Keys方法来迭代存在的所有键。

  2. 如果ID为filter

  3. ,则也可以使用qwsa221

let lists = {
      def453ed: [
        {
          id: "qwsa221",
          name: "Mind"
        },
        {
          id: "jwkh245",
          name: "Space"
        }
      ]
    };

let l = Object.keys(lists)
  .map(d => lists[d]
  .find(el => el.id === "qwsa221"))
  
  console.log(l)