1

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
1
  • 1
    If all 3 arrays have same number of elements then you can do a for loop for the length and use the iterator i to access array value by index. Commented Apr 18, 2016 at 16:51

3 Answers 3

1

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]); 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Good to see you again Hodges :)
1

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, e.g.

console.log(result[0]);

1 Comment

Good solution, but I cannot upvote until you address the "Basically automate console.log" statement from the OP.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.