JSFiddle - React, Tailwind, and code Playground
by Aleksey Pshenichnov
JavaScript
if (typeof Object.prototype.find != 'function') {
Object.prototype.find = function (key, val) {
var objects = [];
for (var p in this) {
if (!this.hasOwnProperty(p)) continue;
if (typeof this[p] == 'object') {
objects = objects.concat(this[p].find(key, val));
}
else if (p == key && this[key] == val) {
objects.push(this);
}
}
return objects;
};
}
$(document).ready(function () {
var TestObj = {
"Categories": [{
"Products": [{
"id": "a01",
"name": "Pine",
"description": "Short description of pine."
},
{
"id": "a02",
"name": "Birch",
"description": "Short description of birch."
},
{
"id": "a03",
"name": "Poplar",
"description": "Short description of poplar."
}],
"id": "A",
"title": "Cheap",
"description": "Short description of category A."
},
{
"Product": [{
"id": "b01",
"name": "Maple",
"description": "Short description of maple."
},
{
"id": "b02",
"name": "Oak",
"description": "Short description of oak."
},
{
"id": "b03",
"name": "Bamboo",
"description": "Short description of bamboo."
}],
"id": "B",
"title": "Moderate",
"description": "Short description of category B."
}]
};
var o = TestObj.find('id', 'a02');
console.log(o);
});