gpt4 book ai didi

javascript - 在 JavaScript 中从两个数组生成对象数组

转载 作者:行者123 更新时间:2023-12-02 15:00:18 24 4
gpt4 key购买 nike

我有 2 个数组:

var arrToObjContent = ["DAYOFWEEK","ITEM","QTY","DATEOFPURCHASE","CITY"]
var dayOfWeek="["SUN","MON","TUE","WED","THU","FRI","SAT"]

我一直在尝试使用上面的两个数组创建一个对象数组,如下所示:

{
"DAYOFWEEK":"SUN"
"ITEM":"",
"QTY":"",
"DATEOFPURCHASE":"",
"CITY":""
}, {
"DAYOFWEEK":"MON"
"ITEM":"",
"QTY":"",
"DATEOFPURCHASE":"",
"CITY":""
},{
"DAYOFWEEK":"TUE"
"ITEM":"",
"QTY":"",
"DATEOFPURCHASE":"",
"CITY":""
},{
"DAYOFWEEK":"WED"
"ITEM":"",
"QTY":"",
"DATEOFPURCHASE":"",
"CITY":""
},{
"DAYOFWEEK":"THU"
"ITEM":"",
"QTY":"",
"DATEOFPURCHASE":"",
"CITY":""
},{
"DAYOFWEEK":"FRI"
"ITEM":"",
"QTY":"",
"DATEOFPURCHASE":"",
"CITY":""
},{
"DAYOFWEEK":"SAT"
"ITEM":"",
"QTY":"",
"DATEOFPURCHASE":"",
"CITY":""
}

是否有一个 jQuery/JavaScript 内置函数,我可以将两个数组传递给并获得如上所示的输出?

最佳答案

其实没那么难,看这里:

var arrToObjContent = ["DAYOFWEEK","ITEM","QTY","DATEOFPURCHASE","CITY"],
dayOfWeek = ["SUN","MON","TUE","WED","THU","FRI","SAT"],
i=0,
z,
arrToObjLength = arrToObjContent.length,
dayOfWeekLength = dayOfWeek.length,
jsonObj = {},
newObj,
key,
value;

for(;i<dayOfWeekLength;i++){
newObj = {};
for(z=0;z<arrToObjLength;z++){
key = arrToObjContent[z];

if(key === "DAYOFWEEK") {
value = dayOfWeek[i];
}
else {
value = "";
}
newObj[key] = value;
}
jsonObj[i] = newObj;
}

console.table(jsonObj);

仅供引用,您原来发布的代码中有一些语法错误。

关于javascript - 在 JavaScript 中从两个数组生成对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35469924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com