使用object属性(javascript)从对象数组中删除元素

时间:2014-06-21 22:49:26

标签: javascript jquery arrays

拥有一系列对象:

{ 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)示例非常感谢! 谢谢!

1 个答案:

答案 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"}))

有用的链接:


不太有用但有用的链接: