[英]javascript how to convert array into object
good morning everyone, I know this question was asked several times, but I tried to take a look and I could not solve the problem.大家早上好,我知道这个问题被问了好几次,但我试图看一下,我无法解决问题。 I'm using an owlCarousel library to iterate through a dynamic wordpress gallery.
我正在使用 owlCarousel 库来遍历动态 wordpress 库。 this is the standard code at the moment:
这是目前的标准代码:
var owl = jQuery('.owl-carousel');
owl.owlCarousel({
margin: 10,
loop: true,
responsive: {
0: {
items: 1
},
600: {
items: 2
},
1000: {
items: 3
},
1000: {
items: 4
}
}
})
everything works normally making me view 4 images in the gallery.一切正常,让我在图库中查看 4 张图片。 I would like to create as many items as the number of posts of my custom post type in wordpress, so I created a variable called baratto_obj.n_activity where an array of requested objects arrives with a custom loop.
我想在 wordpress 中创建与我的自定义帖子类型的帖子数量一样多的项目,因此我创建了一个名为baratto_obj.n_activity的变量,其中请求的对象数组通过自定义循环到达。 so I tested this code:
所以我测试了这段代码:
jsonObj = [];
jQuery(baratto_obj.n_attivita).each(function(index) {
item = {
items: index +1
}
jsonObj.push(item);
});
console.log(jsonObj)
what arrives is an array of objects:到达的是一个对象数组:
(3) [{…}, {…}, {…}]
0: {items: 1}
1: {items: 2}
2: {items: 3}
but I can't transform it this way:但我不能这样改造它:
{
0: {
items: 1
},
600: {
items: 2
},
1000: {
items: 3
},
1000: {
items: 4
}
so as to give it as a parameter to the owlCarousel function.以便将其作为参数提供给owlCarousel function。 the end result would be something like this
最终结果将是这样的
owl.owlCarousel({
margin: 10,
loop: true,
responsive: myobject
})
Someone would have the patience to give me a tip.有人会耐心地给我小费。 Thanks in advance
提前致谢
You could assign the array to an object.您可以将数组分配给 object。 This preserves the indices as properties.
这会将索引保留为属性。
var array = [{ items: 1 }, { items: 2 }, { items: 3 }], object = Object.assign({}, array); console.log(object);
Unless I'm missing something in your question and examples you should be creating your empty JSON object like one of these ways:除非我在您的问题和示例中遗漏了某些内容,否则您应该像以下方式之一一样创建空的 JSON object:
var objectA = {}
var objectB = new Object()
Your example is creating an empty array but it looks like you need all JSON, not any array of JSON objects.您的示例正在创建一个空数组,但看起来您需要所有 JSON,而不是任何 JSON 对象数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.