简体   繁体   中英

Remove an object from an object array using index?

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?

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);

(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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM