我有一个包含对象的数组,该对象包含一个也包含对象的数组。当对象数组内的数组中的对象的值为111时,我想返回第一个数组内的整个对象。
下面的代码显示了第一个数组中的一个示例对象。
[
{
"id":11,
"bookingNumber":"1210",
"arrivalDate":"2018-09-17T22:00:00.000Z",
"departureDate":"2019-09-18T22:00:00.000Z",
"customerId":2,
"fields":[
{
"value":"111",
"display_name":"RoomNumber"
},
{
"value":"otherValue",
"display_name":"PersonInfo"
}
]
}
]
我的尝试返回未定义:
const guest = guestGroups.forEach(function (guestGroup) {
guestGroup.fields.filter(function (fields) {
if (fields.value === roomNumber)
return guestGroup;
});
});
答案 0 :(得分:1)
您需要检查some
数组中的fields
是否具有您要查找的value
:
const valueToFind = '111';
const arr=[{"id":11,"bookingNumber":"1210","arrivalDate":"2018-09-17T22:00:00.000Z","departureDate":"2019-09-18T22:00:00.000Z","customerId":2,"fields":[{"value":"111","display_name":"RoomNumber"},{"value":"otherValue","display_name":"PersonInfo"}]}]
const foundObject = arr.find(
({ fields }) => fields.some(
({ value }) => value === valueToFind
)
);
console.log(foundObject);