我有这个数组[“ 12345678”,“ 87654321”] 而且我想将每个索引注入itemId类别的对象中,并再次遍历该对象,将第二个索引放入另一个itemId类别。
var myArray = ["12345678", "87654321", "12345678"]
var idArray =[]
var arrayLength = myArray.length;
for (var i =0; i < arrayLength; i++) {
let idElement = myArray[i]
idArray.push(idElement);
console.log(idElement);
let multipleitems = {
Request: {
Details: {
id: idArray,
amount: 1
},
}
};
给我这个输出
Request: {Details: {Id: ["12345678", "12345678", "12345678" ], amount: 1}}
是否可以根据myArray中有多少索引来遍历“细节很多次”以获得该输出
{"Request":{"Details":[{"Id":"12345678","amount":1},{"itemId":"87654321","amount":1},{"Id":"12345678","amount":1}]}}
答案 0 :(得分:3)
这是非常基本的array map()操作。您每次迭代都会返回一个新对象,而map()本身会返回一个新数组
var myArray = ["12345678", "87654321", "12345678"];
let multipleitems = {
Request: {
Details: myArray.map(id => ({id, amount:1}) )
}
};
console.log(multipleitems)