Note: the below code return all the objects that has at least one key with its value matching the keyword. The partial-searching is done here.
TestObj = {
"products" :
[
{
"id": "PR001",
"name": "product1",
"category": "category1",
"subcategory": "subcategory1",
"description": "hello",
"price": "price1",
"image": "image1",
"discount": "discount1"
},
{
"id": "hellooo",
"name": "product2",
"category": "category2",
"subcategory": "subcategory2",
"description": "hellonnnnn",
"price": "price2",
"image": "image2",
"discount": "discount2"
},
{
"id": "PR003",
"name": "product3",
"category": "category3",
"subcategory": "subcategory3",
"description": "Nohello",
"price": "price3",
"image": "image3",
"discount": "discount3"
}
]
};
var keys = Object.keys(TestObj.products[0]);
function getObjects(obj, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], val));
}
else if (obj[i].indexOf(val)>-1) {
if(containsObject(obj, objects)==false)
{
objects.push(obj);
}
}
}
return objects;
}
function containsObject(obj, list) {
var i;
for (i = 0; i < list.length; i++) {
if (list[i] === obj) {
return true;
}
}
return false;
}
var searchResult = getObjects(TestObj, 'hello');
console.log(searchResult);

No comments:
Post a Comment