Javascript 使用其名称/值从数组中删除项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6310623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
remove item from array using its name / value
提问by G-Man
I have the following array
我有以下数组
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
How can I remove an item from this array using its name or id ?
如何使用名称或 id 从此数组中删除项目?
Thank you
谢谢
回答by John Strickler
Created a handy function for this..
为此创建了一个方便的功能..
function findAndRemove(array, property, value) {
array.forEach(function(result, index) {
if(result[property] === value) {
//Remove from array
array.splice(index, 1);
}
});
}
//Checks countries.result for an object with a property of 'id' whose value is 'AF'
//Then removes it ;p
findAndRemove(countries.results, 'id', 'AF');
回答by Rocket Hazmat
Array.prototype.removeValue = function(name, value){
var array = $.map(this, function(v,i){
return v[name] === value ? null : v;
});
this.length = 0; //clear original array
this.push.apply(this, array); //push all elements except the one we want to delete
}
countries.results.removeValue('name', 'Albania');
回答by c-smile
Try this:
尝试这个:
var COUNTRY_ID = 'AL';
countries.results =
countries.results.filter(function(el){ return el.id != COUNTRY_ID; });
回答by ScottLee
Try this.(IE8+)
试试这个。(IE8+)
//Define function
function removeJsonAttrs(json,attrs){
return JSON.parse(JSON.stringify(json,function(k,v){
return attrs.indexOf(k)!==-1 ? undefined: v;
}));}
//use object
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
countries = removeJsonAttrs(countries,["name"]);
//use array
var arr = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
arr = removeJsonAttrs(arr,["name"]);
回答by NDB Sites
You can delete by 1 or more properties:
您可以删除 1 个或多个属性:
//Delets an json object from array by given object properties.
//Exp. someJasonCollection.deleteWhereMatches({ l: 1039, v: '3' }); ->
//removes all items with property l=1039 and property v='3'.
Array.prototype.deleteWhereMatches = function (matchObj) {
var indexes = this.findIndexes(matchObj).sort(function (a, b) { return b > a; });
var deleted = 0;
for (var i = 0, count = indexes.length; i < count; i++) {
this.splice(indexes[i], 1);
deleted++;
}
return deleted;
}
回答by KXL
This that only requires javascript and appears a little more readable than other answers. (I assume when you write 'value' you mean 'id')
这只需要 javascript 并且看起来比其他答案更具可读性。(我假设当你写“值”时,你的意思是“id”)
//your code
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
// solution:
//function to remove a value from the json array
function removeItem(obj, prop, val) {
var c, found=false;
for(c in obj) {
if(obj[c][prop] == val) {
found=true;
break;
}
}
if(found){
delete obj[c];
}
}
//example: call the 'remove' function to remove an item by id.
removeItem(countries.results,'id','AF');
//example2: call the 'remove' function to remove an item by name.
removeItem(countries.results,'name','Albania');
// print our result to console to check it works !
for(c in countries.results) {
console.log(countries.results[c].id);
}
回答by Siva Anand
it worked for me..
它对我有用..
countries.results= $.grep(countries.results, function (e) {
if(e.id!= currentID) {
return true;
}
});
回答by Penny Liu
You can do it with _.pullAllBy.
你可以用_.pullAllBy做到这一点。
var countries = {};
countries.results = [
{id:'AF',name:'Afghanistan'},
{id:'AL',name:'Albania'},
{id:'DZ',name:'Algeria'}
];
// Remove element by id
_.pullAllBy(countries.results , [{ 'id': 'AL' }], 'id');
// Remove element by name
// _.pullAllBy(countries.results , [{ 'name': 'Albania' }], 'name');
console.log(countries);
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
回答by Muzaffer GALATA
Maybe this is helpful, too.
也许这也有帮助。
for (var i = countries.length - 1; i--;) {
if (countries[i]['id'] === 'AF' || countries[i]['name'] === 'Algeria'{
countries.splice(i, 1);
}
}
回答by Headshota
you can use delete operator to delete property by it's name
您可以使用 delete 运算符按名称删除属性
delete objectExpression.property
or iterate through the object and find the value you need and delete it:
或遍历对象并找到所需的值并将其删除:
for(prop in Obj){
if(Obj.hasOwnProperty(prop)){
if(Obj[prop] === 'myValue'){
delete Obj[prop];
}
}
}