[英]How to add objects into an array through loop in Javascript $.each?
I am a beginner programmer trying to transfer four properties from my JSONP array into a new array for every item. 我是一名初学者程序员,试图将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
})
}
}
});
My end goal is to get bigarray
to get all all items in objects like below: 我的最终目标是获取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"}]
Question 题
1. How do I add objects based on the number of items in the array? 1.如何根据数组中的项目数添加对象?
2. Any other methods are welcomed, I will accept the answer even if $.even is replaced with a for loop. 2.欢迎使用任何其他方法,即使$ .even被for循环替换,我也将接受答案。
You are looking for the push method, which can be used to add a value to the end of an array. 您正在寻找push方法,该方法可用于将值添加到数组的末尾。
bigArray = []; // create the array
object = {foo: 'bar'}; // create an object
bigArray.push({object}); // push the object onto the end of the array
You can use push() to add item into the array and you can even modify your code as below 您可以使用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.