1

i have some code and request from multiple url, and result data is array , if i use result.push(data) the result will give [[{Data1:a,Data2:b}],[{Data1:c,Data2:d}]] how to merged data become array like [{Data1:a,Data2:b},{Data1:c,Data2:d}]

var url_api = [<?=$urlapi;?>];
var responses = [];

for(var i = 0; i < url_api.length; i++){
  getTarif(url_api[i]);
}

function getTarif(link){
  $.ajax({
    type: 'GET',
    url: link,
    dataType: 'json',
    error: function () {
      alert('Unable to load url :'+link+', Incorrect path or invalid url');
    },
    success: function (data) {
       responses.push(data.data);
    }
  });
}

1 Answer 1

1

You can use the spread syntax - responses.push(...data.data); - to add individual items to the responses arrays:

function getTarif(link){
  $.ajax({
    type: 'GET',
    url: link,
    dataType: 'json',
    error: function () {
      alert('Unable to load url :'+link+', Incorrect path or invalid url');
    },
    success: function (data) {
       responses.push(...data.data);
    }
  });
}
Sign up to request clarification or add additional context in comments.

3 Comments

hey can i ask you something ? after i push the data and console.log its show empty array, but if i expand is showing 2 data . and if i call the array its not showing anything .
This is an async operation, so console.logging the results after getTarif shows you the current status (empty). When you you expand it, the console refreshes the result. Calling it is an sync operation that will get you the original empty array. Whatever you want to do with the data, add to a function, and call inside the success block. You should also learn about promises or async/await.
success: function (data) { responses.push(...data.data); fn(responses); // your logic } However, you should learn promises and async/await.

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.