简体   繁体   中英

Check if the clicked value exist in JSON object

I'm working on creating a function that checks if the value printed on the existence of a JSON list. So if I for example click on the value "1" it will get the object stored on that value in the JSON list. In the example under, I should get the json-object with 'Title: "Test2" and etc.

    var testInfo= {
    test: [
        {
            title: "Test1",
            image: "..",
            info: "Test1",
            price: 100
        }, {
            title: "Test2",
            image: "..",
            info: "Test2",
            price: 100
        }, {
            title: "Test3",
            image: "..",
            info: "Test3",
            price: 100
        }, {
            title: "Test4",
            image: "..",
            info: "Test4",
            price: 100
        } 
    ]   
}

For now I have this for calling on the function check if the value is existing.

$("#test" + [i]).append('<div id="testtest"><img src=".." id="testT" onClick="writeOutJson('+ [i] +')"/></div>');



function writeOutJson(id){
    var test = testInfo.test;
    if(id == WHAT SHOULD I WRITE HER TO CHECK IF THE VALUE EXIST?){
        // Some code to print out
    }
}

The function works if I write if(id == 1) and then click on the one with id one. But I need it to be able to check all values. So if I click on the one with id 4 it will print out the one that starts with "Title: Test 4". Hope you understand what I am trying to do.

You can use .grep()

Finds the elements of an array which satisfy a filter function. The original array is not affected.

Code to check value exists

var arr = jQuery.grep(arr, function( value, index ) {
  return value.title == "Test" + id; 
});
var valueExists = arr.length > 0; 

I actually got it to work by adding a for-loop before:

for( i = 0; i < test.length; i++){
    if(id == [i]){
    }
}

Don't know if this the best way to do it, but I get the results that I want.

您可以使用$.inArray()进行试用:

 if($.inArray(id, test) !== -1){

I would suggest to iterate over the array and compare the strings like this:

function writeOutJson(id) {
    var test = testInfo.test;
    for(var i = 0; i < test.length; i++) {
         if(test[i].info == ("Test" + id)) {
             // Some code to print out
             break;
         }
    }
}

Also, I would not create the div the way you do (using an onClick tag in the html). Instead use jQuery .click() method somehow like this:

$("#test" + [i]).append($('<div id="testtest"><img src=".." id="testT"/></div>').click(function() {
     writeOutJson(i);
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM