1

I have an array of objects that look like this.

Here is a pen just in case.

  myArray = [
     {text: 'person', role: 'person'},
     {text: 'hobby', role: 'hobbies'},
     {text:'food', role: 'foods'},
     {text:'cars', role: 'vehicles'}
  ]

How can i make it so that if a certain condition is false, the object with cars will be hidden and if it is true then return the array as it is?

3
  • if (condition) myArray = [/*something else*/];? Commented Dec 13, 2019 at 18:08
  • Is ther another or dynamic way of doing this? what if my array is really long and i want to do it in just one place without having to declare this all over the place? Commented Dec 13, 2019 at 18:12
  • Declare the parts that you want in both places in one array and the parts that you want only in one place in another array, then merge (.concat()) them in the place where you want both parts. Commented Dec 13, 2019 at 18:20

2 Answers 2

2
  myArray = [
     {text: 'person', role: 'person'},
     {text: 'hobby', role: 'hobbies'},
     {text:'food', role: 'foods'},
     {text:'cars', role: 'vehicles'}
  ]
  if(condition){
    return myArray.filter( item => item.text !== 'cars')
  }else{
    return myArray;
  }
Sign up to request clarification or add additional context in comments.

2 Comments

"if it is true then return the array as it is" - I believe your logic is reversed.
Thank you so much!!
2

You can use the filter function :

if(condition===false) {
  myArray = myArray.filter(o=>o.text!=="cars");
}

Comments

Your Answer

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