[英]How to remove Objects from an array of objects using JavaScript?
I have an array of objects where some objects are undefined and I want to know how to remove them i got it how many of them but don't know how to remove them from an array of objects.我有一个对象数组,其中一些对象未定义,我想知道如何删除它们,我知道它们中有多少,但不知道如何从对象数组中删除它们。 i know this method to use but i want some more standard way to do it
我知道使用这种方法,但我想要一些更标准的方法来做到这一点
const data = [
{
roleDoc:{
name:"A"
}
},
{ roleDoc: undefined }
,{
roleDoc:{
name:"c"
}
},{
roleDoc:{
name:"c"
}
},
{ roleDoc: undefined },
,{
roleDoc:{
name:"c"
}
}
]
const xy = []
data.forEach(item => {
if(item.roleDoc !== undefined){
xy.push(item)
}
else{
console.log('hello')
}
})
console.log(xy)
expected output is预期输出是
const data = [
{
roleDoc: {
name: "A"
}
},
,
{
roleDoc: {
name: "c"
}
},
{
roleDoc: {
name: "c"
}
},
,
{
roleDoc: {
name: "c"
}
}
];
You can use .filter()
to remove undefined
ones.您可以使用
.filter()
删除undefined
的。
Try the following:请尝试以下操作:
const data = [{ roleDoc:{ name:"A" } }, { roleDoc: undefined } ,{ roleDoc:{ name:"c"}},{roleDoc:{name:"c"} }, { roleDoc: undefined },{ roleDoc:{name:"c"}}]; const result = data.filter(e => e.roleDoc); console.log(result);
I hope this helps!我希望这有帮助!
You could do with Array#filter
and !!
你可以用
Array#filter
和!!
only matched valid只匹配有效
const data = [ { roleDoc:{ name:"A" } }, { roleDoc: undefined } ,{ roleDoc:{ name:"c" } },{ roleDoc:{ name:"c" } }, { roleDoc: undefined },{ roleDoc:{ name:"c" } }]; let res = data.filter(a=> !!a.roleDoc); console.log(res)
You could use a function programming approach using the Array.filter
function:您可以使用使用
Array.filter
函数的函数编程方法:
const data = [
{
roleDoc: {
name: "A"
}
},
{
roleDoc: undefined
},
{
roleDoc: {
name: "c"
}
},
{
roleDoc: {
name: "c"
}
},
{
roleDoc: undefined
},
{
roleDoc: {
name: "c"
}
}
];
const arrayWithoutUndefineds = data.filter(el => typeof el.roleDoc !== 'undefined');
console.log(arrayWithoutUndefineds);
Note that the expression used could be simplied.请注意,可以简化所使用的表达式。 However, so it it clear what it happening I will leave it there.
然而,所以很清楚发生了什么我会把它留在那里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.