基于Array Javascript创建对象

时间:2017-04-25 08:49:55

标签: javascript arrays object for-loop typescript

let Array: any = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]

如何将此数组转换为如下所示的对象:

let Object: any = {
    time: {
        headerName: ""
    },
    monday: {
        headerName: "Monday"
    },
    tuesday: {
        headerName: "Tuesday"
    },
    wednesday: {
        headerName: "Wednesday"
    },
    thursday: {
        headerName: "Thursday"
    },
    friday: {
        headerName: "Friday"
    },
    saturday: {
        headerName: "Saturday"
    },
    sunday: {
        headerName: "Sunday"
    }
};

任何想法的人?对不起我是一个安静的JavaScript新手。如何编写for循环以便我可以实现此结果?在此先感谢你们

4 个答案:

答案 0 :(得分:4)

var result = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"].reduce(function (acc, element) { 
     acc[element] = {};
     acc[element].headerName=element;
     return acc;
}, {time: ""});
console.log(result);

您可以使用reduce转换为JavaScript中的对象。

any.reduce(function (acc, element) { 
     acc[element] = {};
     acc[element].headerName=element;
     return acc;
}, {time: ""})

答案 1 :(得分:3)

只需尝试这个



var any = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
var outputObj = { //create a new object with one default value
  time: {
    headerName: ""
  }
};
any.forEach(function(item) { //iterate the any array and then keep adding key and values to new Object
  outputObj[item] = {
    headerName: capitalizeFirstLetter(item)
  };
});

function capitalizeFirstLetter(string) {
  return string.charAt(0).toUpperCase() + string.slice(1);
}

console.log( outputObj );




答案 2 :(得分:2)



var any = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];

var res ={};
res['time'] ={headername:""};
any.map(function(a){
res[a] = {headername:a}

})
console.log(res)




答案 3 :(得分:0)

Using For loop.

function toObject(arr) {
  var rv = {};
  for (var i = 0; i < arr.length; ++i)
    if (arr[i] !== undefined) rv[arr[i]] = {"headerName":arr[i]};
  console.log(rv);
}
toObject(["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]);