繁体   English   中英

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

[英]How to access an array of objects which is a key-value pair

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

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

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

使用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) }) }) 

您可以使用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]) 

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

  2. 如果存在多个id qwsa221 ,也可以使用filter

 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) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM