如何动态创建对象?

时间:2017-10-08 12:42:42

标签: javascript arrays loops object

这是我的代码:

 var x = 0;
 function ref() {
   setIntervel(ref, array[x]);
   x++;
   // codes to update chart
 }

我想动态地制作它:

var parts = ['Identifiers', 'Names', 'Emails'];

window["identifier_websites"] = ["aparat", "youtube", "telegram"];
window["name_websites"]       = ["twitter", "instagram", "googleplus", "facebook", "linkedin", "cloob", "stackoverflow", "hammihan", "lenzor", "delgoo"];
window["email_websites"]      = ["email", "gmail", "aol", "chmail"];

这样做可能吗?

3 个答案:

答案 0 :(得分:1)

这个函数来到这里Convert Array to Object你只需要添加一个新的数组来将所有数组合并为一个并在之后使用它。

//var result = new Map(arr.map((i) => [i.key, i.val]));

var parts = ['Identifiers', 'Names', 'Emails'];
var myArrays = [];
window["identifier_websites"] = ["aparat", "youtube", "telegram"];
window["name_websites"]       = ["twitter", "instagram", "googleplus", "facebook", "linkedin", "cloob", "stackoverflow", "hammihan", "lenzor", "delgoo"];
window["email_websites"]      = ["email", "gmail", "aol", "chmail"];

myArrays.push(window.identifier_websites, window.name_websites, window.email_websites);
//console.log(myArrays);
var obj =myArrays.reduce(function(acc, cur, i) {
  acc[parts[i]] = cur;
  return acc;
}, {});
console.log(obj)

答案 1 :(得分:0)

当然,js是动态语言,所以这不仅可行,而且广泛使用,您可以在节点REPL中尝试这样的片段,只需在终端中键入节点。

答案 2 :(得分:0)

如果你试图动态地走动零件来创建一个对象,就可以了。

parts.reduce((acc, k) => {
  var singular = k.substr(0, k.length - 1).toLowerCase() + "_websites";
  acc[k] = window[singular];
  return acc;
}, {});