我想遍历对象的嵌套数组,如果满足条件,我想返回找到的对象所在的第一层的对象。
我该如何实现?
我的尝试:
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
},
{ ...
}
]
},
{ ...
}
]
答案 0 :(得分:2)
您可以使用Array.prototype.find和Array.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));