1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

pls help comparing two json array

Discussion in 'jQuery' started by cris02, Jan 8, 2014.

  1. #1
    json1 = [{'id':1,'name':pedro,'selected':''},{'id':2,'name':juan,'selected':''}, {'id':3,'name':john,'selected':''}];
    Code (markup):
    json2 = [{'id':1,'name':pedro},{'id':3,'name':john,'selected':''}];
    Code (markup):
    I want to check if the name value of json2 is exist in json1 then if exist modify the value of 'selected' keyname from json1 to 'true'.

    Any idea? Please hekp thanks
     
    cris02, Jan 8, 2014 IP
  2. lp1051

    lp1051 Well-Known Member

    Messages:
    163
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    108
    #2
    You can always loop twice through the arrays, so possible code could be:
        json1 = [{'id':1,'name':'pedro','selected':''},{'id':2,'name':'juan','selected':''}, {'id':3,'name':'john','selected':''}];
        json2 = [{'id':1,'name':'pedro'},{'id':3,'name':'john','selected':''}];
        json1 = $.map(json1, function (n, i) {
            $.each(json2, function(j, val) {
                if (val.id == n.id) {
                    n.selected = true;
                    return false;
                }
            })
            return n;
        });
        console.log(json1);
    Code (markup):
    But, as you can see, it is not optimal. Your `json2` variable tells you if the object should be selected or not, so it would be lot better to reformat json2 into:
        json2 = {'1':true, '3':true};
    Code (markup):
    Then you can simplify the code and use:
        json1 = [{'id':1,'name':'pedro','selected':''},{'id':2,'name':'juan','selected':''}, {'id':3,'name':'john','selected':''}];
        json2 = {'1':true, '3':true};
        json1 = $.map(json1, function (n, i) {
            if (n.id in json2) {
                n.selected = true;
            }
            return n;
        });
        console.log(json1);
    Code (markup):
    Hope it helps
     
    Last edited: Jan 13, 2014
    lp1051, Jan 13, 2014 IP