Ответы пользователя по тегу JSON
  • Как проверить наличие объекта в JSON?

    huze
    @huze
    Lead Developer, Crowdspace
    var objects = [
        {
            "id": "34bfd2234234177b17854d52",
            "name": "Miki",
            "lastname": "Adams",
            "profession": "Designer",
            "email": "mmm@gmail.com",
            "online": true,
            "admin": false,
            "createdAt": "Wed Jan 21 2015 19: 24: 56 GMT + 0300(MSK)",
            "updatedAt": "Thu Jan 22 2015 17: 22: 47 GMT + 0300(MSK)",
            "avatar": ""
        },
        {
            "id": "54bfd2d81b9b177b17854d52",
            "name": "Artur",
            "lastname": "Altman",
            "profession": "Designer",
            "email": "aaa@gmail.com",
            "online": true,
            "admin": false,
            "createdAt": "Wed Jan 21 2015 19: 24: 56 GMT + 0300(MSK)",
            "updatedAt": "Thu Jan 22 2015 17: 22: 47 GMT + 0300(MSK)",
            "avatar": ""
        }
    ];
    
    Array.prototype.containsObjectWithId = function(id){
        return !!this.filter(function(el){
            return el.hasOwnProperty('id') && el.id == id
        }).length;
    }
    
    console.log(objects.containsObjectWithId('54bfd2d81b9b177b17854d52')) // true
    console.log(objects.containsObjectWithId('ok, this id do not exist')) // false

    jsfiddle.net/r1duq6cy
    Ответ написан