1

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);
          },
    })
}; 
3
  • Where is your console.log where you are checking for the names / array? I only see a console.log in the error handler. Sep 10, 2019 at 15:47
  • Sorry I failed to include it Sep 10, 2019 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? Sep 10, 2019 at 17:24

3 Answers 3

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.

2

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
  • Can also use var items = data.d.results; and arrayOfNames.push(items[i].Name); - but six of one, half a dozen to the other.
    – vapcguy
    Sep 30, 2021 at 15:37
2

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...
}
3
  • If you wanted to put in multiple values to that array, how would you do it? The return only seems to allow for a single one. And I don't mean in the context of name[0], name[1], name[2], but like if you wanted to do name[0], title[0], location[0] and then do name[1], title[1], location[1]... can the map function do that?
    – vapcguy
    Sep 14, 2021 at 17:01
  • 1
    I think i understand you. You want to return for each result more data. Then in return item.Name you should return an object instead. Something like return {name: item.Name, prop2: item.Prop2} and more and more... but yo use it it would be (in this case) arrayOfNames[0].name , or arrayOfNames[0].prop2 ... an array of objects. Is what you are asking for?
    – Mikel
    Sep 15, 2021 at 20:31
  • Yeah, that's it! Thanks - just had to make sure of that syntax on how to set, then grab those! Appreciated!
    – vapcguy
    Sep 17, 2021 at 6:41

Your Answer

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

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