push only unique elements in an array

后端 未结 6 1385
-上瘾入骨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 14:44

    would this accomplish what you're looking for? https://jsfiddle.net/gukv9arj/3/

    x = [
        {"id":"item1","val":"Items"},
        {"id":"item1","val":"Items"},
        {"id":"item2","val":"Items"}
    ];    
    
    var clickId = [];
    var list = JSON.parse(x);
    $.each(list, function(index, value){
        if(clickId.indexOf(value.id) === -1){
            clickId.push(value.id);
        }
    });
    

提交回复
热议问题