如果两个值都不存在,我如何推入数组?这是我的数组:

[
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" }
]

如果我试图再次推入数组的名字:“tom”或文本:“tasty”,我不希望发生任何事情…但如果这两个都不存在那么我就输入。push()

我该怎么做呢?


当前回答

someArray = [{a: 'a1 value', b: {c: "c1 value"},
             {a: 'a2 value', b: {c: "c2 value"}]
newObject = {a: 'a2 value', b: {c: "c2 value"}}

//New object which needs check for duplicity

let isExists = checkForExists(newObject) {
    return someArray.some(function(el) {
        return el.a === newObject.a && el.b.c === newObject.b.c;
    });
}
// write your logic here 
// if isExists is true then already object in an array else you can add

其他回答

你可以用一个自定义方法扩展Array原型:

// check if an element exists in array using a comparer function
// comparer : function(currentElement)
Array.prototype.inArray = function(comparer) { 
    for(var i=0; i < this.length; i++) { 
        if(comparer(this[i])) return true; 
    }
    return false; 
}; 

// adds an element to the array if it does not already exist using a comparer 
// function
Array.prototype.pushIfNotExist = function(element, comparer) { 
    if (!this.inArray(comparer)) {
        this.push(element);
    }
}; 

var array = [{ name: "tom", text: "tasty" }];
var element = { name: "tom", text: "tasty" };
array.pushIfNotExist(element, function(e) { 
    return e.name === element.name && e.text === element.text; 
});

不确定速度,但stringification + indexOf是一个简单的方法。首先将数组转换为字符串:

let strMyArray = JSON.stringify(myArray);

然后,对于一系列属性-值对,您可以使用:

if (strMyArray.indexOf('"name":"tom"') === -1 && strMyArray.indexOf('"text":"tasty"') === -1) {
   myArray.push({ name: "tom", text: "tasty" });
}

查找整个对象更简单:

if (strMyArray.indexOf(JSON.stringify(objAddMe) === -1) { 
   myArray.push(objAddMe);
}

我知道这是一个非常老的问题,但如果你使用ES6,你可以使用一个非常小的版本:

[1,2,3].filter(f => f !== 3).concat([3])

非常简单,首先添加一个过滤器,删除项目-如果它已经存在,然后通过concat添加它。

下面是一个更现实的例子:

const myArray = ['hello', 'world']
const newArrayItem

myArray.filter(f => f !== newArrayItem).concat([newArrayItem])

如果你的数组包含对象,你可以像这样调整过滤器函数:

someArray.filter(f => f.some(s => s.id === myId)).concat([{ id: myId }])
someArray = [{a: 'a1 value', b: {c: "c1 value"},
             {a: 'a2 value', b: {c: "c2 value"}]
newObject = {a: 'a2 value', b: {c: "c2 value"}}

//New object which needs check for duplicity

let isExists = checkForExists(newObject) {
    return someArray.some(function(el) {
        return el.a === newObject.a && el.b.c === newObject.b.c;
    });
}
// write your logic here 
// if isExists is true then already object in an array else you can add

短的例子:

if (typeof(arr[key]) === "undefined") {
  arr.push(key);
}