我希望循环访问一个对象并使用jQuery输入到某些索引。我正在使用Sweet Alert 2和链接模式,但我需要动态生成标题。标题在下面的数组中。
SA2使用的对象如下:
var steps = [{
title: 'Questions',
input: 'radio',
inputOptions: inputOptions,
}]
我想'每个'在方括号之后的某种形式。
["Washing Machine diagnosis", "Washing Machine type", "Have you ever had an engineer look at this fault?", "Has an engineer looked at this appliance in the last 6 months?", "Has anybody that is not a qualified repair engineer attempted to repair the Washing Machine?", "Duration of problem", "When did you purchase this Washing Machine?", "Do you have a receipt?"]
Essentailly我需要创建:
var steps = [{
title: 'Washing Machine diagnosis',
input: 'radio',
inputOptions: inputOptions,
},
{
title: 'Washing Machine diagnosis',
input: 'radio',
inputOptions: inputOptions,
}]
感谢您的帮助
答案 0 :(得分:2)
您可以使用Array.map()
ES6
var result = ["Washing Machine diagnosis", "Washing Machine type", "Have you ever had an engineer look at this fault?", "Has an engineer looked at this appliance in the last 6 months?", "Has anybody that is not a qualified repair engineer attempted to repair the Washing Machine?", "Duration of problem", "When did you purchase this Washing Machine?", "Do you have a receipt?"]
.map(e => ({title:e,input:"radio",inputOptions:{}}));
console.log(result)

ES5
var result = ["Washing Machine diagnosis", "Washing Machine type", "Have you ever had an engineer look at this fault?", "Has an engineer looked at this appliance in the last 6 months?", "Has anybody that is not a qualified repair engineer attempted to repair the Washing Machine?", "Duration of problem", "When did you purchase this Washing Machine?", "Do you have a receipt?"]
.map(function(e){
return {title:e,input:"radio",inputOptions:{}};
});
console.log(result)

答案 1 :(得分:1)
您需要一个模板对象:
var step = {
title : '',
input : 'radio',
inputOptions : inputOptions
};
然后你将遍历数组:
var titles = [
"Washing Machine diagnosis",
"Washing Machine type",
...
"Do you have a receipt?"
];
var steps = titles.map((title) => {
var clone = Object.assign({}, step);
clone.title = title;
return clone;
});
或者如果您不喜欢assign()
答案 2 :(得分:0)
这个怎么样
$.each(steps, function(i, step){
step.title = myArray[i];
});
这使用JQuery循环遍历数组。
答案 3 :(得分:0)
我不确定我是否理解你的问题但是这个怎么样
const titles = ["Washing Machine diagnosis", "Washing Machine type", "Have you ever had an engineer look at this fault?", "Has an engineer looked at this appliance in the last 6 months?", "Has anybody that is not a qualified repair engineer attempted to repair the Washing Machine?", "Duration of problem", "When did you purchase this Washing Machine?", "Do you have a receipt?"]
const steps = titles.map((title) => {
return {
title,
input: 'radio',
inputOptions
}
})