如何映射和过滤对象数组?

时间:2019-05-11 12:56:06

标签: javascript arrays object ecmascript-6 functional-programming

对不起,但是我有一个假的问题。 我需要从json响应中迭代对象,并仅获取那些满足某些条件的对象。 响应是这样的:

  result = [
      {
        "type": "EVENT",
        "id": "001",
        "tags": [
            {
            "id": "98765",
            "name": "home"
            }
        ]
      },
      {
        "type": "EVENT",
        "id": "002",
        "tags": [
            {
            "id": "7654",
            "name": "contact"
            }
        ]
      },
      {
        "type": "EVENT",
        "id": "003",
        "tags": []
      }
    ]

我只需要使用类型为“事件”且标记中的名称属性为home的那些

我尝试了地图和过滤器,但没有得到想要的结果

const eventType = result.filter(type => type.type == 'EVENT')
 const nameFilter = 
    eventType.map(item => item.tags)
    .filter(sub => sub.length) // remove empty []
    .map(subarray => subarray.map(element =>  element.name )
    .filter(element => element == 'home')); 

结果:

 [
  ['home'], // dosen t work for me, because need all the object
  [],
  []
 ]

3 个答案:

答案 0 :(得分:3)

您可以使用filter遍历数组。使用some检查tags数组中至少一个元素是否具有值为name的属性"home"

result.filter(o => o.type === "EVENT" && o.tags.some(s => s.name === "home"));

演示:

let result = [{"type":"EVENT","id":"001","tags":[{"id":"98765","name":"home"}]},{"type":"EVENT","id":"002","tags":[{"id":"7654","name":"contact"}]},{"type":"EVENT","id":"003","tags":[]}];

let filtered = result.filter(o => o.type === "EVENT" && o.tags.some(s => s.name === "home"));

console.log( filtered );

答案 1 :(得分:1)

您只需要filter()并使用find()some()来检查标记中的存在名称。

var filter = result.filter(c=> c.type == "EVENT" && c.tags.find(d=>d.name == 'home'));
var filter = result.filter(c=> c.type == "EVENT" && c.tags.some(d=>d.name == 'home'));

let result=  [
      {
        "type": "EVENT",
        "id": "001",
        "tags": [
            {
            "id": "98765",
            "name": "home"
            }
        ]
      },
      {
        "type": "EVENT",
        "id": "002",
        "tags": [
            {
            "id": "7654",
            "name": "contact"
            }
        ]
      },
      {
        "type": "EVENT",
        "id": "003",
        "tags": []
      }
    ]
    
    var filter = result.filter(c=> c.type == "EVENT" && c.tags.find(d=>d.name == 'home'));
    
    console.log(filter);

答案 2 :(得分:-1)

如果您只是想从根数组中选择元素,则使用filter是合适的方法。 如果您还想转换结果(例如选择TAG对象),则可以使用flatMap

result.flatMap( e => (e.type == 'EVENT' && e.tags.some(t => t.name==='home')) ? e.tags : [] )