Array.push() if does not exist?

2019-01-03 23:43发布

How can I push into an array if neither values exist? Here is my array:

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

If I tried to push again into the array with either name: "tom" or text: "tasty", I don't want anything to happen... but if neither of those are there then I want it to .push()

How can I do this?

16条回答
太酷不给撩
2楼-- · 2019-01-04 00:14

You can check the array using foreach and then pop the item if it exists otherwise add new item...

sample newItemValue &submitFields are key,value pairs

> //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});
查看更多
Emotional °昔
3楼-- · 2019-01-04 00:15

Use a js library like underscore.js for these reasons exactly. Use: union: Computes the union of the passed-in arrays: the list of unique items, in order, that are present in one or more of the arrays.

_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]
查看更多
Melony?
4楼-- · 2019-01-04 00:17

Short example:

if (typeof(arr[key]) === "undefined") {
  arr.push(key);
}
查看更多
萌系小妹纸
5楼-- · 2019-01-04 00:19

You can use jQuery grep and push if no results: http://api.jquery.com/jQuery.grep/

It's basically the same solution as in the "extending the prototype" solution, but without extending (or polluting) the prototype.

查看更多
登录 后发表回答