简体   繁体   中英

Delete object from array of multiple objects

I have an array like:

var participants = [
  {username: "john", time: null}, 
  {username: "samira", time: null}, 
  {username: "mike", time: null}, 
  {username: "son", time:null}
]

I want to remove an item by username:

const index = participants.map(x => {

  x.map(y => {
      return y.username;
    })
  }).indexOf(username); //get index of username

participants.splice(index, 1);

Hence, index of username returns "-1", therefore participants array becomes 0?

Expected output, by username: 'son':

[
  {username: "john", time: null}, 
  {username: "samira", time: null}, 
  {username: "mike", time: null}
]

UPDATE:

Turns out my array is within an array, like this

控制台日志阵列

您可以使用数组过滤器功能

participants.filter((item) => item.username !== username))

try this

var username = 'son';

for(var i = 0; i < participants.length; i++) {
    if(participants[i].username == username) {
        participants.splice(i, 1);
        i--;
    }
}

NOTE: filter , map and the like offer code readability while for loops are better performing. Choose according to your specific problem.

您可以使用过滤器方法,也可以使用splice和map:

participants.splice(participants.map(x => x.username).indexOf(username),1);

You can use filter function, but filter doesn't change the original array; so you have to reassign results to the original variable. participants = participants.filter((item) => item.username !== username))

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