0

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"
 }
 }
];
norbitrial
15.2k10 gold badges39 silver badges66 bronze badges
asked Mar 17, 2020 at 16:55

3 Answers 3

1

You could do with Array#filter and !! 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)

answered Mar 17, 2020 at 16:58
Sign up to request clarification or add additional context in comments.

Comments

1

You can use .filter() to remove undefined ones.

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!

answered Mar 17, 2020 at 16:57

Comments

0

You could use a function programming approach using the Array.filter function:

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.

answered Mar 17, 2020 at 16:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.