javascript - 在嵌套对象数组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
},
{ ...
}
]
},
{ ...
}
]
解决方案
您可以使用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));
推荐阅读
- javascript - VueJS如何在使用下拉选择时过滤数组数据
- javascript - 邮递员:您需要启用 JavaScript 才能运行此应用
- ios - 在模态样式演示iOS13上冻结SFSafariViewController上的横向方向
- python - Unabe 在 Beautifulsoup 中解析大表
- android - 检索 JSON 中的特定字段
- javascript - 在我的 Web 应用程序中为不同的打印对象设置本地打印机
- reactjs - Redux Form FieldArray 传递状态问题
- r - 如何存储 Highcharter 地图以便在没有 Internet 连接的情况下使用它们?
- php - 如何在 AJAX 调用后 JSON 值后更新同一页面上的 SESSION 值而不刷新页面
- spring-boot - 我们如何将默认的 Swagger URL 更改为任何其他 URL