0

I am trying to create an array with only the Name properties from a list in SP 2013. I tried using the push method but it has not worked for me. My console prints out the names in an increment style. First line has 1 name ,second 2 names, third 3 names and so on.

Here is my code:

function forLoop(){
  var siteUrl = "http://site/_api/web/lists/GetByTitle('SPRestTest')/items";

      $.ajax({
          url: siteUrl,
          type: "GET",
          async: false,
          headers: {
              "accept": "application/json;odata=verbose"
          },
          success:function(data){
            var arrayOfNames = [];
            for(var i=0;i<data.d.results.length;i++){
              var items = data.d.results[i];
              arrayOfNames.push(items.Name);    

            }

          },
          error: function (err) {
            console.log(err);
          },
    })
}; 
  • Where is your console.log where you are checking for the names / array? I only see a console.log in the error handler. – Dylan Cristy Sep 10 at 15:47
  • Sorry I failed to include it – Ben Segarra Sep 10 at 17:11
  • Can you describe where it is? Is it the line immediately after the arrayOfNames.push(items.Name);? Or edit your question to add the line where it should be? – Dylan Cristy Sep 10 at 17:24
1

Please find below a better solution of what you are trying to achieve.

function forLoop(){
  var siteUrl = "http://site/_api/web/lists/GetByTitle('SPRestTest')/items";

      $.ajax({
          url: siteUrl,
          type: "GET",
          async: false,
          headers: {
              "accept": "application/json;odata=verbose"
          },
          success:function(data){
            var items = data.d.results;
            var arrayOfNames = items.map(function(o){ 
                                   return o["Name"]
                               });
          },
          error: function (err) {
            console.log(err);
          },
    })
}; 

Try executing on all browsers & Please mark this as answer if it helps.

1

You describe a console.log() statement as printing the names in "an increment style", first printing one name, then printing two names, then printing three names, etc.

If the console.log() line that does that occurs immediately after your array.push() line, like so:

var arrayOfNames = [];
for (var i = 0; i < data.d.results.length; i++) {
    var items = data.d.results[i];
    arrayOfNames.push(items.Name);
    console.log(arrayOfNames);
}

then I would say that everything is working as expected, and the push function is working for you.

Let's follow what happens in the code:

  • first, you declare a variable that's an array: var arrayOfNames = [];
  • then you begin a for loop: for (var i = 0; i < data.d.results.length; i++) {
  • now you are in the first pass of the for loop, and i = 0. You use i to get the index 0 item from the data.d.results array: var items = data.d.results[i];
  • you push the Name property of that first item into your arrayOfNames array: arrayOfNames.push(items.Name);
  • then you log the array, which at this point only has one item in it: console.log(arrayOfNames);
  • now you are at the end of the loop, so the loop restarts, but increments i by one, so now i = 1
  • you use i to get the item at index 1 from the results array: var items = data.d.results[i];
  • you push the Name property of that into your array. Now your array has 2 items in it: arrayOfNames.push(items.Name);
  • you log your array, which now has 2 names in it.
  • the loop restarts, but i increments to 2
  • you get the item at index 2 from the results array
  • you push the Name property into your array, so now your array has 3 items
  • you log your array, which now has 3 names in it
  • etc

So you see, if the console.log line where you are checking your array occurs inside the for loop, then what you are describing is exactly what should be happening.

Besides putting that console.log outside the loop, the other minor adjustment I'd make to your code is to declare the arrayOfNames outside the scope of the success function, so you can use it elsewhere in your code. Like this:

function forLoop() {
    var siteUrl = "http://site/_api/web/lists/GetByTitle('SPRestTest')/items";

    var arrayOfNames = []; // declared outside the success function

    console.log('before fetching data', arrayOfNames); // will log an empty array

    $.ajax({
        url: siteUrl,
        type: "GET",
        async: false,
        headers: {
            "accept": "application/json;odata=verbose"
        },
        success: function (data) {
            for (var i = 0; i < data.d.results.length; i++) {
                // change "items" to "item" - singular, because that's what it is, a single item
                var item = data.d.results[i];
                arrayOfNames.push(item.Name);
            } // end the for loop

            console.log('after looping', arrayOfNames); // will log only the full, completed array
        },
        error: function (err) {
            console.log(err);
        },
    });

    // you can access the array outside the success function
    console.log('after fetching data', arrayOfNames); // will log the same array that the 'after looping' log did
};
1

You should try to avoid using ajax sync calls.

Try to do whatever you want in the success callback if is posible.

function forLoop(){
  var siteUrl = "http://site/_api/web/lists/GetByTitle('SPRestTest')/items";

  $.ajax({
      url: siteUrl,
      type: "GET",
      headers: {
          "accept": "application/json;odata=verbose"
      },
      success: function (data) {
        var arrayOfNames = data.d.results.map(function(item) {
          return item.Name;
        });
        console.log(arrayOfNames) // ['name1', 'name2', ...]
        doYourStuffWithArrayOfNames(arrayOfNames);
      },
      error: function (err) {
        console.log(err);
      },
  })
};
function doYourStuffWithArrayOfNames(arrayOfNames) {
  // do stuff...
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.