gpt4 book ai didi

javascript - 如何根据多个对象属性有条件地删除数组中的对象?

转载 作者:行者123 更新时间:2023-11-28 11:06:54 24 4
gpt4 key购买 nike

在 React 上下文中,我尝试渲染一些具有如下结构的对象:

const regions = [
{
displayName: 'NYC',
locations: [
{name: 'thing', isVisible: false},
{name: 'thing1', isVisible: false},
{name: 'thing3', isVisible: false},
],
},
{
displayName: 'Seattle',
locations: [
{name: 'thing', isVisible: true},
{name: 'thing1', isVisible: true},
{name: 'thing3', isVisible: true},
],
....
},
....
];

我的问题是对于第一个具有所有 isVisible: false 的对象的上下文,如果所有 isVisible 值都为 false,是否可以删除整个对象?基本上使用示例,这个对象:

{
displayName: 'NYC',
locations: [
{name: 'thing', isVisible: false},
{name: 'thing1', isVisible: false},
{name: 'thing3', isVisible: false},
],
},

将被删除。

如果是这样,怎么办?如果不能,这可以实现吗?有其他解决方案吗?

最佳答案

数组过滤很简单

// filter only returns regions where the internal function evaluates to true
regions.filter(function(region){
// some returns true if at least one of the elements in the array causes the function below to return true
return region.locations.some(function(location){
return location.isVisible
})
})

问题是您无法将其重新分配给regions,因为它是一个const

关于javascript - 如何根据多个对象属性有条件地删除数组中的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51621913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com