Answer the question
In order to leave comments, you need to log in
How to check if an object exists in JSON?
[
{
id: '34bfd2234234177b17854d52'
name: 'Miki',
lastname: 'Adams',
profession: 'Designer',
email: '[email protected]',
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: '[email protected]',
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: '[email protected]',
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: '',
}
]
Answer the question
In order to leave comments, you need to log in
The necessary information can be found here:
https://developer.mozilla.org/ru/docs/Web/JavaScri...
PS: There is a search by ID in the examples. =)
The same id is used for two objects - is this generally legal?)
On the topic: you must have some kind of criterion (a group of criteria) that allows you to uniquely distinguish one object from another (by its fields) - and usually this is just id.
parse json into an array, go around the resulting array, check for compliance with these unique criteria - it matches, which means this is the object.
var objects = [
{
"id": "34bfd2234234177b17854d52",
"name": "Miki",
"lastname": "Adams",
"profession": "Designer",
"email": "[email protected]",
"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": "[email protected]",
"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
collection.indexOf(object) !== -1
// upd
for (var i = 0, ii = collection.length; i < ii; ++i) {
if (collection[i].id === object.id) {
// your object
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question