Hello, there is a code that loads and iterates json,

jQuery.each(response.items, function(index, item) { text += '<li class="item"><a href="' + item.product.url + '" title="' + item.title + '" class="product-image"><img src="' +image+ '" width="50" alt="' + item.title + '"></li>'; }); 

It is necessary to output data from another json object into it, some "key-values" are the same, for example json 1:

 {[ "id": "123", "title": "qwerty"], [ "id": "456", "title": "asdf"]} 

json 2:

 {[ "id": "123", "img": "http://google.com"], [ "id": "456", "img": "http://vk.com"]} 

It is necessary to sort through the json 1 loop, but take one parameter with json 2 if the id is the same. Help please advice how to do this

    1 answer 1

    It is possible from the original "json'ov", which are arrays of objects as I understood, to collect objects (dictionaries), where the keys - id, and the values ​​of objects entirely. For example:

     // было [ { "id": "123", "title": "qwerty"}, .. // стало { "123": { "id": "123", "title": "qwerty"}, .. 

    It is convenient to find all data by id. Then it will be necessary only to run through all the id from the first, and if there is one with the same id from the second, copy all the fields:

     var json1 = [ { "id": "123", "title": "qwerty"}, { "id": "456", "title": "asdf"}, ]; var json2 = [ { "id": "123", "img": "http://google.com"}, { "id": "456", "img": "http://vk.com"}, ]; function json2dict(J) { var i, el, D = {}; for(i in J) { el = J[i]; D[el.id] = el; } return D; } var D1 = json2dict(json1); var D2 = json2dict(json2); var Ids1 = Object.keys(D1); var Ids2 = Object.keys(D2); var i, id; for( var i = 0; i<Ids1.length; i++) { id = Ids1[i]; if( !!~Ids2.indexOf(id)) { for(attr in D2[id]) { D1[id][attr] = D2[id][attr]; } } } document.getElementById('out').innerText = JSON.stringify( Object.values(D1)); 
     #out{font-family:Courier New,monospace} 
     <div id="out"></div>