简体   繁体   中英

Generate array of objects from two arrays in JavaScript

I've got 2 arrays:

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

I've been trying to create an object array using the above two arrays that looks like this:

{
"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":""
}

Is there a jQuery/JavaScript built-in function that I can pass two arrays to & get the output as above?

It's really not that hard, here you go:

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);

FYI, you had some syntax error in your original posted code.

There's no built-in function to do this, but it is fairly straightforward to do on your own.

var arrToObjContent = ["DAYOFWEEK","ITEM","QTY","DATEOFPURCHASE","CITY"];
var dayOfWeek=["SUN","MON","TUE","WED","THU","FRI","SAT"];
dayOfWeek.map((x) => {
    var obj = {};
    arrToObjContent.forEach((y) => { obj[y] = (y === "DAYOFWEEK")? x : ""; });
    return obj;
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM