我有一个对象,它有服务数组,我检查了是否有任何服务 id 和 offer id 与对象的减少计数值匹配,一旦计数达到零,就需要删除该对象。请检查我的小提琴尝试。我可以减少但在达到零时无法删除
const obj = {
name:'saloon',
services:[
{
sid:1,
offid:20,
count:2
},
{
sid:2,
offid:18,
count:1
},
{
sid:3,
offid:15,
count:3
}
]
}
给定值:基于此服务,并且报价 id 计数应减少,一旦计数达到零需要删除该对象
const servid = 2
const offid = 18
我的代码
obj.services = obj.services.map(data => {
if(data.sid == servid && data.offid == offid ){
return data.count > 1 && {
sid:data.sid,
offide:data.offid,
count:data.count -1
}
}else{
return data
}
})
console.log(obj);
预期结果 :
const result = {
name:'saloon',
services:[
{
sid:1,
offid:20,
count:2
},
{
sid:3,
offid:15,
count:3
}
]
}
使用array#forEach
通过您的阵列中迭代并检查每个sid
和offid
内部服务,在比赛的更新情况下,count
值检查后,如果count
值小于或等于零,如果是,则使用推其索引indexes
数组。之后,您可以遍历indexes
数组并services
使用array#splice
.
const obj = { name:'saloon', services:[ { sid:1, offid:20, count:2 }, { sid:2, offid:18, count:1 }, { sid:3, offid:15, count:3 } ] };
const servid = 2;
const offid = 18;
var indexes = [];
obj.services.forEach(function(service, index) {
if(service.sid === servid && service.offid === offid){
--service.count;
}
if(service.count <= 0)
indexes.push(index);
});
indexes.reverse().forEach(function(index){
obj.services.splice(index, 1);
});
console.log(obj);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句