我有一个像这样的数组:
var participants = [
{username: "john", time: null},
{username: "samira", time: null},
{username: "mike", time: null},
{username: "son", time:null}
]
我要通过用户名删除项目:
const index = participants.map(x => {
x.map(y => {
return y.username;
})
}).indexOf(username); //get index of username
participants.splice(index, 1);
因此,用户名的索引返回“ -1”,因此参与者数组变为0?
按用户名“ son”的预期输出:
[
{username: "john", time: null},
{username: "samira", time: null},
{username: "mike", time: null}
]
更新:
原来我的数组在数组之内,就像这样
答案 0 :(得分:3)
您可以使用数组过滤器功能
participants.filter((item) => item.username !== username))
答案 1 :(得分:0)
尝试
var username = 'son';
for(var i = 0; i < participants.length; i++) {
if(participants[i].username == username) {
participants.splice(i, 1);
i--;
}
}
注意:filter
,map
等提供了代码可读性,而for
循环的执行效果更好。根据您的具体问题进行选择。
答案 2 :(得分:0)
您可以使用filter方法,也可以结合使用拼接和贴图:
Flux<Tuple2<T, Integer>> sourceFlux = ...; //assuming key/count represented as `Tuple2`
Flux<Tuple2<T, Integer>> aggregated = sourceFlux.compose(source -> {
//having this state inside a compose means it will not be shared by multiple subscribers
AtomicReference<T> last = new AtomicReference<>(null);
return source
//use "last seen" state so split into windows, much like a `groupBy` but with earlier closing
.windowUntil(i -> !i.getT1().equals(last.getAndSet(i.getT1())), true)
//reduce each window
.flatMap(window -> window.reduce((i1, i2) -> Tuples.of(i1.getT1(), i1.getT2() + i2.getT2()))
});
答案 3 :(得分:0)
您可以使用过滤器功能,但过滤器不会更改原始数组;因此您必须将结果重新分配给原始变量。 参与者=参与者。过滤器((item)=> item.username!==用户名))