Home > Enterprise >  Remove an object from an object array using index?
Remove an object from an object array using index?

Time:12-16

I want to remove 3rd object from an array in which the color is red. I want to remove it using the index as some objects may not have an _id attribute and other attributes are not unique among them.

[
  {  color: "BLUE"
     imageURL: "/uploads/image-1639632524718.png"
     inStock: 4
     _id: "61b9bff23b027548ed2f737e"
  },
  {  color: "green"
     imageURL: "/uploads/image-1639561204805.png"
     inStock: 6
     _id: "61ba098f3b027548ed2f737f"
  },
  {  color: "Red"
     imageURL: "/uploads/image-1639647424471.png"
     inStock: 6
  },
  {  color: "Star Light"
     imageURL: "/uploads/image-1639650244179.png"
     inStock: 60
  }
]  

After removing the object array will look like.

[
  {  color: "BLUE"
     imageURL: "/uploads/image-1639632524718.png"
     inStock: 4
     _id: "61b9bff23b027548ed2f737e"
  },
  {  color: "green"
     imageURL: "/uploads/image-1639561204805.png"
     inStock: 6
     _id: "61ba098f3b027548ed2f737f"
  },
  {  color: "Star Light"
     imageURL: "/uploads/image-1639650244179.png"
     inStock: 60
  }
]  

How can I do this?

CodePudding user response:

this splice function does that

someArray.splice(index, 1)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

CodePudding user response:

Use Array.splice() method to remove item from specified position.

const list = [
  {  color: "BLUE",
     imageURL: "/uploads/image-1639632524718.png",
     inStock: 4,
     _id: "61b9bff23b027548ed2f737e"
  },
  {  color: "green",
     imageURL: "/uploads/image-1639561204805.png",
     inStock: 6,
     _id: "61ba098f3b027548ed2f737f"
  },
  {  color: "Red",
     imageURL: "/uploads/image-1639647424471.png",
     inStock: 6
  },
  {  color: "Star Light",
     imageURL: "/uploads/image-1639650244179.png",
     inStock: 60
  }
];

const remove = (arr, index) => arr.splice(index, 1);
remove(list, 2);
console.log("list after removal: ", list);

CodePudding user response:

(Once you've fixed your data structure - it's not an array, and you're missing commas...)

You can filter out all those objects that aren't located at that index.

const data=[{color:"BLUE",imageURL:"/uploads/image-1639632524718.png",inStock:4,_id:"61b9bff23b027548ed2f737e"},{color:"green",imageURL:"/uploads/image-1639561204805.png",inStock:6,_id:"61ba098f3b027548ed2f737f"},{color:"Red",imageURL:"/uploads/image-1639647424471.png",inStock:6},{color:"Star Light",imageURL:"/uploads/image-1639650244179.png",inStock:60}];

const out = data.filter((obj, i) => i !== 2);

console.log(out);

  • Related