简体   繁体   中英

Concat first item of array to first itiem of second array JavaScript

how can I concat more rationally first item of array to first of second array and so on? Basically automate console.log here is the code:

$("button#search").on("click", function(){
var inputVal = $("input#text").val();
$.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&search=" + inputVal +"&limit=5&namespace=0&format=json&callback=?", function(json) {
    var itemName = $.each(json[1], function(i, val){    
    })
    var itemDescription = $.each(json[2], function(i, val){ 
    })
    var itemLink = $.each(json[3], function(i, val){
    })
    console.log(itemName[0] + " " + itemDescription[0] + " " + itemLink[0]);
    console.log(itemName[1] + " " + itemDescription[1] + " " + itemLink[1]);
    console.log(itemName[2] + " " + itemDescription[2] + " " + itemLink[2]);
    console.log(itemName[3] + " " + itemDescription[3] + " " + itemLink[3]);
    console.log(itemName[4] + " " + itemDescription[4] + " " + itemLink[4]);
    })//EOF getJSON
});//EOF button click

I believe this is what you are looking for:

for (var i = 0; i < itemName.length; i++) {
  console.log(itemName[i] + " " + itemDescription[i] + " " + itemLink[i]); 
}

If arrays have the same length, you could use map

var result = $.map(json[1], function(i, val){
    var row = val + " " + json[2][i] + " " + json[3][i];
    console.log(row);
    return row;
}

Also you can use that result later, eg

console.log(result[0]);

Using es6 you can do the following:

(in your getJson callback):

function (json) {
    const [value, optionsJ, descriptionsJ, linksJ] = json;
    let whatIwant = [];

    // choose one to loop through since you know they will all be the same length:
    optionsJ.forEach(function (option, index) {
        whatIwant.push({option: option, description: descriptionJ[index], link: linksJ[index]});
    });

    // use whatIwant here**
}

Your new whatIwant array will then contain objects for each set.

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