gpt4 book ai didi

javascript - 从对象数组中删除空条目

转载 作者:行者123 更新时间:2023-12-02 21:35:18 24 4
gpt4 key购买 nike

我下面有以下对象数组(组件),我想删除所有空条目。我该如何去做呢?我正在尝试以下操作:

  static deleteNullComponents(components) {
return components.filter(function (el) {
return el['components'] != null;
});
}

但我收到错误:TypeError:components.filter 不是函数。我该如何修复它?

[
{
"components": [
null,
{
"componentId": "navbar-zJNm0HaP",
"componentIndex": 1,
"componentName": "app-builder-navbar",
},
null,
null,
null,
{
"componentId": "features-MJU8gcYR",
"componentIndex": 5,
"componentName": "app-builder-features",
},
null,
{
"componentId": "features-2hsUdwaT",
"componentIndex": 7,
"componentName": "app-builder-features",
},
null,
{
"componentId": "footer-dLvoLZ16",
"componentIndex": 9,
"componentName": "app-builder-footer",
},
null
],
"name": "Home"
},
{
"components": [
null,
{
"componentId": "navbar-UBdYplVp",
"componentIndex": 1,
"componentName": "app-builder-navbar",
},
null,
{
"componentId": "features-mmEzByeO",
"componentIndex": 3,
"componentName": "app-builder-features"
},
null,
{
"componentId": "features-GZKgh9lV",
"componentIndex": 5,
"componentName": "app-builder-features"
},
null,
{
"componentId": "footer-IyrNODRQ",
"componentIndex": 9,
"componentName": "app-builder-footer",
},
null
],
"name": "About"
}
]

最佳答案

componentspageComponents

中数组项内的数组属性

所以你需要两个循环(forEach/map/filter 等实际上只是遍历数组)

因此,对于 pageComponents 数组中的每个项目,您希望过滤该项目的 components 属性中的值

此外,在过滤器函数中,您不需要返回原始数组,因为您没有更改原始数组,而是更改了其中的嵌套数组

class MyService {  
static deleteNullComponents(components) {
components.forEach(obj =>
obj.components = obj.components.filter(item => item !== null)
)
}
}

let pageComponents = [
{
"components": [
null,
{
"componentId": "navbar-zJNm0HaP",
"componentIndex": 1,
"componentName": "app-builder-navbar",
},
null,
null,
null,
{
"componentId": "features-MJU8gcYR",
"componentIndex": 5,
"componentName": "app-builder-features",
},
null,
{
"componentId": "features-2hsUdwaT",
"componentIndex": 7,
"componentName": "app-builder-features",
},
null,
{
"componentId": "footer-dLvoLZ16",
"componentIndex": 9,
"componentName": "app-builder-footer",
},
null
],
"name": "Home"
},
{
"components": [
null,
{
"componentId": "navbar-UBdYplVp",
"componentIndex": 1,
"componentName": "app-builder-navbar",
},
null,
{
"componentId": "features-mmEzByeO",
"componentIndex": 3,
"componentName": "app-builder-features"
},
null,
{
"componentId": "features-GZKgh9lV",
"componentIndex": 5,
"componentName": "app-builder-features"
},
null,
{
"componentId": "footer-IyrNODRQ",
"componentIndex": 9,
"componentName": "app-builder-footer",
},
null
],
"name": "About"
}
]

MyService.deleteNullComponents(pageComponents)
console.log(pageComponents)

关于javascript - 从对象数组中删除空条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60516345/

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