Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get data in json array by ID

I have a problem, may you help me! I have a json array:

"category" : [
{
    id: 1,
    product: [{id : product_1, type : ball}] 
},
{
    id : 2,
    product :[{id : product_2, type : pen}]
}
]

My problem is: if i have a link such as: http://test/category/1 then , How can I do to get product information by category with id = 1 ? Thanks for any suggestion :)

like image 845
JaclBlack Avatar asked Nov 17 '11 08:11

JaclBlack


3 Answers

This is a way to do it in one line and without using for:

function filterById(jsonObject, id) {return jsonObject.filter(function(jsonObject) {return (jsonObject['id'] == id);})[0];}

Then if you want to get, for example, the object with id=2, you just use:

var selectedObject = filterById(yourJson['category'], 2);

And then selectedObject will get this value, as per your example:

{
    id : 2,
    product :[{id : product_2, type : pen}]
}

There is a downside: Old browsers, such as IE8, don't support filter() so you need to add this polyfill code for old browser compatibility: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Polyfill

like image 162
OMA Avatar answered Oct 22 '22 01:10

OMA


Assuming your data structure looks like this:

var data = {
    "category" : [
    {
        id: 1,
        product: [{id : product_1, type : ball}] 
    },
    {
        id : 2,
        product :[{id : product_2, type : pen}]
    }
    ]
}

Then, you can find the item in the category array with id == 1 by searching through the array like this:

function findId(data, idToLookFor) {
    var categoryArray = data.category;
    for (var i = 0; i < categoryArray.length; i++) {
        if (categoryArray[i].id == idToLookFor) {
            return(categoryArray[i].product);
        }
    }
}

var item = findId(data, 1);
// item.id, item.type
like image 28
jfriend00 Avatar answered Oct 22 '22 01:10

jfriend00


If you save your array of categories in categories JS variable, you can filter this array based on simple JavaScript (with no jQuery) like that:

var result = categories.filter(function(element){
    if (element.id == 2){
        return true;
    } else {
        return false;
    }
});

and then in result[0].product you will have array of products that are within specific category.

See this jsfiddle for a proof.

PS. filter() method is not available in all browsers, you may need to apply some code that will make it available if needed and not found. Here is some article on Mozilla Developers Network on the details of filter() and the code you need to make it work on old browsers: MDN: filter().

like image 33
Tadeck Avatar answered Oct 22 '22 00:10

Tadeck