如果两个值都不存在,我如何推入数组?这是我的数组:
[
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" },
{ name: "tom", text: "tasty" }
]
如果我试图再次推入数组的名字:“tom”或文本:“tasty”,我不希望发生任何事情…但如果这两个都不存在那么我就输入。push()
我该怎么做呢?
您可以使用foreach检查数组,然后弹出项目,如果它存在,否则添加新的项目…
newItemValue &submitFields是键值对
> //submitFields existing array
> angular.forEach(submitFields, function(item) {
> index++; //newItemValue new key,value to check
> if (newItemValue == item.value) {
> submitFields.splice(index-1,1);
>
> } });
submitFields.push({"field":field,"value":value});
我有这个问题,我做了一个简单的原型,使用它,如果你喜欢它
Array.prototype.findOrPush = function(predicate, fallbackVal) {
let item = this.find(predicate)
if(!item){
item = fallbackVal
this.push(item)
}
return item
}
let arr = [{id: 1}]
let item = arr.findOrPush(e => e.id == 2, {id: 2})
console.log(item) // {id: 2}
// will not push and just return existing value
arr.findOrPush(e => e.id == 2, {id: 2})
conslog.log(arr) // [{id: 1}, {id: 2}]
如果你的项目包含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')
正是出于这些原因,使用像underscore.js这样的js库。union:计算传入数组的并集:在一个或多个数组中出现的唯一项的列表。
_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]
使用数组是很容易做到的。函数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")