繁体   English   中英

如何通过Javascript $ .each中的循环将对象添加到数组中?

[英]How to add objects into an array through loop in Javascript $.each?

我是一名初学者程序员,试图将JSONP数组中的四个属性转移到每个项目的新数组中。

$.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                                             
            })
        }
    }
});

我的最终目标是获取bigarray来获取对象中的所有所有项,如下所示:

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"}]


1.如何根据数组中的项目数添加对象?
2.欢迎使用任何其他方法,即使$ .even被for循环替换,我也将接受答案。

您正在寻找push方法,该方法可用于将值添加到数组的末尾。

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

您可以使用push()将项目添加到数组中,甚至可以如下修改代码

$.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
                });

            })
        }
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM