JavaScript 清除数组对象
Posted
技术标签:
【中文标题】JavaScript 清除数组对象【英文标题】:JavaScript clean array object 【发布时间】:2021-04-17 11:14:31 【问题描述】:您好,我有一个包含对象数组的对象数组。例如,如果我的用户搜索皮革,我想知道如何将属性清空。
我的结果:
let cars = [
name: 'Volvo',
equipments: [
name: 'saddleries', options: [title: 'leather'] ,
name: 'wheels', options: [title: 'sliver'] ,
name: 'motor', options: [] ]
];
我想要这个结果:
let cars = [
name: 'Volvo',
equipments: [
name: 'saddleries', options: [title: 'leather'] ,
name: 'wheels', options: [title: 'sliver'] ,
];
请问如何删除我的数据?谢谢
【问题讨论】:
不要破坏您的帖子。通过在本网站上发布,您已不可撤销地授予 Stack Exchange 网络以CC BY-SA 4.0 license 分发该内容的权利,只要它认为合适即可。有关删除的替代方法,请参阅:I've thought better of my question; can I delete it? 【参考方案1】:检查此代码
let cars = [
name: 'Volvo',
equipments: [
name: 'saddleries', options: [title: 'leather'] ,
name: 'wheels', options: [title: 'sliver'] ,
name: 'motor', options: [] ]
];
cars.forEach((c) =>
c.equipments = c.equipments.filter(e => e.options.length !== 0);
)
console.log(cars)
【讨论】:
【参考方案2】:试试这个:
var cars =
name: 'Volvo',
equipments: [
name: 'saddleries',
options: [
title: 'leather'
]
,
name: 'wheels',
options: [
title: 'sliver'
]
,
name: 'motor',
options: []
,
name: 'handles',
options: []
]
;
carsCopy = Object.assign([], cars.equipments)
var count = 0
cars.equipments.forEach(function(data, index)
if (data.options.length === 0)
carsCopy.splice(index - count, 1);
count++;
)
console.log(carsCopy)
【讨论】:
在没有选项的情况下尝试两个或更多元素(按顺序)。 修复了问题!以上是关于JavaScript 清除数组对象的主要内容,如果未能解决你的问题,请参考以下文章
JavaScript之清除数组空值项包括空数组空对象isArraystringifypushcontinuelength