如何通过迭代创建对象

时间:2019-01-29 01:24:57

标签: javascript loops

如果我想要三个以上的对象怎么办?我可以以某种方式循环播放吗?

let newArr = []

let newObj1 = {};  let newObj2 = {};  let newObj3 = {};

newArr.push(newObj1);
newArr.push(newObj2);
newArr.push(newObj3);

console.log(newArr);

如果我添加第3个循环,我的阵列将制动,如何将其折合? 这是我的完整代码:

  

let arr = [       {fullName:{姓氏:“ xxx”,firstName:'yyy',middleName:'zzz'}},       {fullName:{surname:'XXX',firstName:'YYY',middleName:'ZZZ'}}]让boolObj = {fullName:{surname:true,firstName:true,   middleName:false}} let loc = {“ fullName.surname”:“Прізвище”,   “ fullName.middleName”:“По-батькові”}

     

let newArr = [] newObj1 = {}; newObj2 = {}; newObj3 = {};

     

for(var i = 0; i ${Object.keys(arr[i])}.${arrObjObjKeys[0]};       让boolObjStr3 = ${Object.keys(arr[i])}.${arrObjObjKeys[2]};       让ojbStr1 = value${i+1}       if(boolObjStr1 === locObjKeys [0] && arrObjObjValues [0]!==''){           newObj1.name = loc [boolObjStr1];           newObj3.name = loc [boolObjStr3];           newObj2.name = arrObjObjKeys [1];       }       for(let j = 0; j <3; j ++){           if(boolObjValues [0] === true){               newObj1 [ojbStr1] = arr [i] [arrObjKeys] [arrObjObjKeys [j-2]];           }           if(boolObjValues [1] === true){               newObj2 [ojbStr1] = arr [i] [arrObjKeys] [arrObjObjKeys [j-1]];           }           if(boolObjValues [2] === true){               newObj3 [ojbStr1] = arr [i] [arrObjKeys] [arrObjObjKeys [j]];           }       }} newArr.push(newObj1); newArr.push(newObj2); newArr.push(newObj3);

     

console.log(newArr);

将来我要添加对象,例如:

  

let arr = [       {fullName:{姓氏:'xxx',firstName:'yyy',middleName:'zzz',数据:{xxx:'Boom'}}}   ]

这些类似

的代码之后
  

newObj1 = {}; newObj2 = {}; newObj3 = {};   成为不好的解决方案?

但是如果我遍历

  

newObj1 = {}; newObj2 = {}; newObj3 = {};

这将是3个循环,我的代码将被破坏。 请告知如何解决?

1 个答案:

答案 0 :(得分:1)

似乎是一个相当普遍/基本的问题,但是为什么不尝试一个简单的for循环呢?

let  arr = [];

for (var x = 0; x < 100; x++) {
  const object = new Object();
  arr.push(object);
}