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

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

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

我该怎么做呢?


当前回答

如果不在列表中,则添加

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

[...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")
 

我知道这是一个非常老的问题,但如果你使用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 }])

我的选择是使用.includes()扩展数组。正如@Darrin Dimitrov所建议的原型:

Array.prototype.pushIfNotIncluded = function (element) {
    if (!this.includes(element)) {
      this.push(element);
    }
}

记住include来自es6,在IE上不起作用: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

对于字符串数组(但不是对象数组),你可以通过调用.indexOf()来检查一个项是否存在,如果不存在,则将该项推入数组:

var newItem = "NEW_ITEM_TO_ARRAY"; var array = ["OLD_ITEM_1", "OLD_ITEM_2"]; array.indexOf(newItem) === -1 ?array.push(newItem): console.log("此项已存在"); console.log(数组)

如果不在列表中,则添加

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

[...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])]
}