Home > Mobile >  how to remove object from array of objects
how to remove object from array of objects

Time:01-16

i have a problem with an array and looking for little help. I need to make a function to remove an object from array and if this object is not in array i get return msg So far i have something like this:

const arrays = { 
  array:[
   { name: 'a', price: 100 },
   { name: 'b', price: 200 },
   { name: 'c', price: 300 },
  ],
removeArray(arrayName) {
  for (let element of this.array){ 
    if (element.name === arrayName) {
    this.array.splice(arrayName, 1);
    }
  }
   return `Array ${arrayName.name} is not in base!;`
}, 
} 

console.log(arrays.removeArray({name:'b', price: 200}));

Can i ask for a little help with this?

CodePudding user response:

You need to wrap your returned string in

`
quotes (backticks) to trigger string interpolation.

const arrays = {

array: [

{ name: 'a', price: 100 },

{ name: 'b', price: 200 },

{ name: 'c', price: 300 },

], 

removeArray(arrayName) { 

  for (let element of this.array) { 
    if (element.name === arrayName) { 
      this.array.splice(arrayName, 1); 
    } 
  } 

  return `Array ${arrayName.name} is not in base!`; 
}, 
} 
console.log(arrays.removeArray({name:'b', price: 200}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

CodePudding user response:

In JavaScript, the array pop() method deals with removing the last element of the array, in other words, the array.pop() method removes the last object of the array in JavaScript. After removing the element the array.pop() function also returns the element and updates the length of the array.

  • Related