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

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

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

我该怎么做呢?


当前回答

如果你的项目包含lodash,使用unionBy方法会很简单

import {unionBy} from "lodash";

let arrayObj = [
    { name: "jhon", text: "guitar"},
    { name: "paul", text: "bass" },
    { name: "george", text: "guitar" }
];

// this object will be added to the array
arrayObj = unionBy(arrayObj, [{name: 'ringo', text: 'drums'}], 'name')

// this object will be ignored because already exists  
arrayObj = unionBy(arrayObj, [{name: "jhon", text: "guitar"}], 'name')

其他回答

对于字符串数组(但不是对象数组),你可以通过调用.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(数组)

推送后删除重复项

如果你已经有一个包含重复项的数组,将对象数组转换为字符串数组,然后使用Set()函数消除重复项:

let arr_obj = [
    { name: "tom", text: "tasty" }, 
    { name: "tom", text: "tasty" }
]

let arr_str = arr_obj.map(JSON.stringify)

let arr_unique = [...new Set(arr_str)].map(JSON.parse) 

推前检查

如果你到目前为止没有重复的元素,你想在推入一个新元素之前检查重复:

let arr_obj = [
    { name: "tom", text: "tasty" },
    { name: "tim", text: "tusty" }
]

let new_obj = { name: "tom", text: "tasty" }

let arr_str = arr_obj.map(JSON.stringify)

!arr_str.includes(JSON.stringify(new_obj)) && arr_obj.push(new_obj)

如果没有结果,可以使用jQuery grep和push: http://api.jquery.com/jQuery.grep/

这基本上是与“扩展原型”解决方案相同的解决方案,但没有扩展(或污染)原型。

如果你需要一些简单的东西,而不想扩展数组原型:

// Example array
var array = [{id: 1}, {id: 2}, {id: 3}];

function pushIfNew(obj) {
  for (var i = 0; i < array.length; i++) {
    if (array[i].id === obj.id) { // modify whatever property you need
      return;
    }
  }
  array.push(obj);
}

使用数组是很容易做到的。函数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")