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

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

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

我该怎么做呢?


当前回答

不确定速度,但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);
}

其他回答

如果不在列表中,则添加

对于一个简单值的列表,它是一行程序…

[...new Set([...someArray, someElement])]

JavaScript的用法:

var myArray = ['bill','bob']
var alreadyIn = [...new Set([...myArray, 'bob'])] // ['bill','bob']
var notAlreadyIn = [...new Set([...myArray, 'peter'])] // ['bill','bob','peter']

TypeScript文本(注意include vs includes):

interface Array<T> {
  include(element: T): Array<T>
}
Array.prototype.include = function (element: any): any[] {
  return [...new Set([...this, obj])]
}

...但对于对象来说,情况就复杂多了

[...new Set([...someArray.map((o) => JSON.stringify(o)),
    JSON.stringify(someElement)]).map((o) => JSON.parse(o))

TypeScript文本处理任何事情:

Array.prototype.include = function (element: any): any[] {
  if (element && typeof element === 'object')
    return [
      ...new Set([
        ...this.map((o) => JSON.stringify(o)),
        JSON.stringify(element),
      ]),
    ].map((o) => JSON.parse(o))
  else return [...new Set([...this, element])]
}

使用数组是很容易做到的。函数findIndex,它以函数作为参数:

var arrayObj = [{name:"bull", text: "sour"},
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" }
]
var index = arrayObj.findIndex(x => x.name=="bob"); 
// here you can check specific property for an object whether it exist in your array or not

index === -1 ? arrayObj.push({your_object}) : console.log("object already exists")
 

短的例子:

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

你可以用一个自定义方法扩展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; 
});

推动动态

var a = [
  {name:"bull", text: "sour"},
  {name: "tom", text: "tasty" },
  {name: "Jerry", text: "tasty" }
]

function addItem(item) {
  var index = a.findIndex(x => x.name == item.name)
  if (index === -1) {
    a.push(item);
  }else {
    console.log("object already exists")
  }
}

var item = {name:"bull", text: "sour"};
addItem(item);

用简单的方法

var item = {name:"bull", text: "sour"};
a.findIndex(x => x.name == item.name) == -1 ? a.push(item) : console.log("object already exists")

如果数组只包含基元类型/简单数组

var b = [1, 7, 8, 4, 3];
var newItem = 6;
b.indexOf(newItem) === -1 && b.push(newItem);