数组中最后一个具有相同值的对象


const obj = [
{
id:1,
info : [
{
status:"open",
value:300
},
{
status:"closed",
value:1
},
{
status:"open",
value:100
}
]
},
{
id:2,
info : [
{
status:"open",
value:40
},
{
status:"closed",
value:1
},
{
status:"open",
value:150
},
{
status:"open",
value:250
},
{
status:"closed",
value:10
}
]
}
]

我想做的是根据最后一个状态为打开的值进行筛选。

例如,如果我想查找大于200的值,它应该只返回id为2的值。因为id为2的对象的最后一个状态值是250。

我试过这样的方法,但状态是通过所有打开的来过滤的。

const filtered = obj.filter(o => {
return o.info.find(value => {
if (value.status == "open") {
if(value.value > 200){
return true;
}
};
});
});
console.log(filtered)
const filtered = obj.filter(o => {
for (let i = o.info.length - 1; i >= 0; i--) {
if (o.info[i].status === 'open') {
return o.info[i].value > 200
}
}
return false;
});

您可以找到最后一个"打开";记录,在反转数组后执行find()

const data = [{
id: 1,
info: [
{ status: "open", value: 20 }, 
{ status: "closed", value: 1 },
{ status: "open", value: 100 }
]
}, {
id: 2,
info: [
{ status: "open", value: 40 },
{ status: "closed", value: 1 },
{ status: "open", value: 150 },
{ status: "open", value: 250 },
{ status: "closed", value: 10 }
]
}];
const fn = (data, value) => data.filter(
({info}) => [...info.reverse()].find(
({status}) => status === 'open'
)?.value > value
).map(({id}) => id);
console.log(fn(data, 200));

请注意,reverse()会就地更改阵列。为了避免原始数据被修改,我将数组扩展到一个新数组中。

最新更新