首页 > 解决方案 > 在嵌套对象数组javascript函数方式的第一层获取数组对象

问题描述

我想遍历一个嵌套的对象数组,如果满足条件,我想返回找到的对象所在的第一层的对象。

我怎样才能做到这一点?

我的尝试:

getLayoutByTableId(tableId: number) {
   return this.layouts.map(function(layout) {
     return layout.tables.filter(function (table) {
       if (table.id === tableId) {
         return layout;
       }
     });
   })
};

它返回满足条件的表对象。

嵌套对象数组:

[  
   {  
      "id":31,
      "stationId":31,
      "tables":[  
         {  
            "id":652,
            "number":"040",
            "x":1285,
            "y":527,
            "length":98,
            "breadth":69,
            "rotation":0,
            "shape":"rectangle",
            "translateX":0,
            "translateY":0,
            "masterId":null,
            "seats":4,
            "groupingActive":false
         },
         { ...
         }
      ]
   },
   { ...
   }
]

标签: javascriptfunctional-programming

解决方案


您可以使用Array.prototype.findArray.prototype.some来使用现有的库函数:

const data = [{id:31,stationId:31,tables:[{id:652,number:"040",x:1285,y:527,length:98,breadth:69,rotation:0,shape:"rectangle",translateX:0,translateY:0,masterId:null,seats:4,groupingActive:false},{}]},{}];

const getLayout = id => data.find(l => l && l.tables && l.tables.some(t => t.id === id));

console.log(getLayout(652));
console.log(getLayout(1111));


推荐阅读