push only unique elements in an array

后端 未结 6 1382
-上瘾入骨i
-上瘾入骨i 2021-01-19 14:25

I have array object(x) that stores json (key,value) objects. I need to make sure that x only takes json object with unique key. Below, example \'id\' is the key, so i don\'t

6条回答
  •  孤街浪徒
    2021-01-19 15:07

    You can't use inArray() because you are searching for an object.

    I'd recommend rewriting a custom find using Array.some() as follows.

    var x = [{"id":"item1","val":"Items"},{"id":"item1","val":"Items"},{"id":"item1","val":"Items"}]    
    
    var clickId = "item1";
    var found = x.some(function(value) {
      return value.id === clickId;
    });
    alert(found);

提交回复
热议问题