0

I am a beginner programmer trying to transfer four properties from my JSONP array into a new array for every item.

$.ajax({
    url: etsyURL,
    dataType: 'jsonp',
    success: function(data) {
        if (data.ok) {
            var a = (data.results);
            //create a parent array to store all objects
            var bigarray = [];

            $.each(a, function(i, item) {
                //assign values from response to variables
                var atitle = item.title;
                var aurl = item.url;
                var aimg = item.Images[0].url_75x75;
                var aprice = item.price;

                //create an object
                var object = {
                    title: atitle,
                    url: aurl,
                    img: aimg,
                    price: aprice
                };

                //add the object into big array for every each item, unsure                                             
            })
        }
    }
});

My end goal is to get bigarray to get all all items in objects like below:

bigarray = [{title:"xbox", url:"www.web.com", pic:"www.pic.com/w.png",price:"100"}, {title:"ps4", url:"www.web.com", pic:"www.pic.com/p.png",price:"110"}]

Question
1. How do I add objects based on the number of items in the array?
2. Any other methods are welcomed, I will accept the answer even if $.even is replaced with a for loop.

3
  • bigarray[] = object; Commented Jan 27, 2017 at 7:21
  • if data.results is an array you don't need $.each() -> Array.prototype.map(), otherwise use $.map() (+ .get()) Commented Jan 27, 2017 at 7:23
  • Use the push function Commented Jan 27, 2017 at 9:18

2 Answers 2

1

You can use push() to add item into the array and you can even modify your code as below

$.ajax({
    url: etsyURL,
    dataType: 'jsonp',
    success: function(data) {
        if (data.ok) {
            var a = (data.results);
            //create a parent array to store all objects
            var bigarray = [];

            $.each(a, function(i, item) {
                //add the object into big array for every each item, unsure 
                bigarray.push({
                   title: item.title,
                    url: item.url,
                    img: item.Images[0].url_75x75,
                    price: item.price
                });

            })
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

You are looking for the push method, which can be used to add a value to the end of an array.

bigArray = []; // create the array
object = {foo: 'bar'}; // create an object
bigArray.push({object}); // push the object onto the end of the array

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.