拥有一系列对象:
{ sid:11, scode:"code", sname:"Sam" },
{ sid:12, scode:"code", sname:"Sam" },
{ sid:13, scode:"code", sname:"Sam" },
{ sid:14, scode:"code", sname:"Sam" },
{ sid:13, scode:"code", sname:"Sam" },
{ sid:139, scode:"code", sname:"Jake"}
{ sid:134, scode:"code", sname:"Jake"}
需要从这个数组中删除只有sname的对象:“Sam”和sid:13。 结果得到下一个:
{ sid:11, scode:"code", sname:"Sam" },
{ sid:12, scode:"code", sname:"Sam" },
{ sid:14, scode:"code", sname:"Sam" },
{ sid:139, scode:"code", sname:"Jake"}
{ sid:134, scode:"code", sname:"Jake"}
Javascript(或jQuery)示例非常感谢! 谢谢!
答案 0 :(得分:3)
Array#filter
示例强>
var array = [{ sid:11, scode:"code", sname:"Sam" },
{ sid:12, scode:"code", sname:"Sam" },
{ sid:13, scode:"code", sname:"Sam" },
{ sid:14, scode:"code", sname:"Sam" },
{ sid:13, scode:"code", sname:"Sam" },
{ sid:139, scode:"code", sname:"Jake"},
{ sid:134, scode:"code", sname:"Jake"}]
var newArray = array.filter(function(element){
if (element.sid === 13 && element.sname === "Sam")
return false
return true
})
console.log(newArray)
另一个例子
这是另一个例子,使用数组原型中的不同函数来创建一个类似于Underscores reject方法的函数。
var reject = function(array, params) {
return array.filter(function(element) {
return !Object.keys(params).map(function(key){
return params[key] === element[key]
}).reduce(function(memo, bool){
return memo & bool
})
})
}
console.log(reject(array, {sid: 13, sname: "Sam"}))
Array.prototype.filter
Documentation