[{
id: 1,
data: "hoge"
},{
id : 3,
data: "hogehogehoge"
},{
id: 4,
data: "fugafuga"
}];
If there is such data, for example, would it be possible to delete the id:3
data?
a=[{
id: 1,
data: "hoge"
},{
id : 3,
data: "hogehogehoge"
},{
id: 4,
data: "fugafuga"
}];
a. removeDataById(3)
↓Results
a = [{
id: 1,
data: "hoge"
},{
id: 4,
data: "fugafuga"
}];
function removeById(array,id){
for(vari=array.length-1;i>=0;i--){
if(array[i].id==id)
array.splice(i,1)
}
}
Note the direction of the loop.
Although it is not standard, you can also use Array.prototype.filter
.
Firefox, Chrome, Opera, Safari, IE9 or higher.
The Array.prototype.filter
polyfill is located in Array.prototype.filter() - JavaScript|MDN.
vara=[{
id: 1,
data: "hoge"
}, {
id : 3,
data: "hogehogehoge"
}, {
id: 4,
data: "fugafuga"
}];
// filter argument —Specifies the function that returns true for the element that you want to leave
varb = a.filter(function(entry) {return entry.id!=3;});
// *Note that a does not change itself, but creates a new array b.
document.querySelector('#result').innerHTML=JSON.stringify(b);
<divid="result"></div>
Array.prototype.removeById(id){
for(vari=this.length-1;i>=0;i--){
if(this[i].id==id)
This.splice(i,1)
}
}
Also, I would like to propose a solution with splice
.
function removeById(array,id){
for(vari=array.length-1;i>=0;i--){
if(array[i].id===id){
array.splice(i,1);
}
}
}
var array = [{
id: 1,
data: "hoge"
}, {
id : 3,
data: "hogehogehoge"
}, {
id: 4,
data: "fugafuga"
}];
removeById(array,3);
console.log(array);
© 2024 OneMinuteCode. All rights reserved.