2

So I can create a whole bunch of empty objects that are independent with my code below. Is there a better way to do this? Or is this the only method?

var array = [];

for (let i = 0; i < 5; i++)
{
 array.push("temp" + i);
}


for (let item of array)
{
 eval(`${item} = new Object();`);
}

temp0.first = 1;
temp4.last = "last";

for (let item of array)
{
 console.log(eval(item));
}
A. L
  • 11,695
  • 23
  • 85
  • 163
  • Obviously it's not the *only* way. The fact that it uses `eval` is a good sign that it's nowhere near the best way to structure things. – nnnnnn Feb 19 '17 at 05:43
  • What is purpose of `eval(${item} = new Object(););`? – guest271314 Feb 19 '17 at 05:43
  • @nnnnnn I'm on the side that `eval` is not inherently evil, but just easily exploited by those that don't know what they're doing. – A. L Feb 19 '17 at 05:44
  • I agree that `eval()` isn't inherently evil, but it is almost never the best approach. Why are you trying to create separate variables like that rather than making them all properties of some master object or items in an array? – nnnnnn Feb 19 '17 at 05:45
  • @guest271314 I could change `new Object()` to `{}` but that's not really the issue. It's to create a whole heap of objects assigned to different variables. So if i did something like `var o1 = o2 = o3 = {}` they would all point to the same object. – A. L Feb 19 '17 at 05:45
  • @nnnnnn I'm not creating it for any real purpose atm, but it's more of a 'what if' scenario I thought up. A master object might be better though. – A. L Feb 19 '17 at 05:46
  • Still not gathering purpose of `eval()`, or what issue is. Destructuring assignment can be used to reference an object by a variable name. – guest271314 Feb 19 '17 at 05:46
  • @guest271314 - OP was trying to declare variables with dynamic names. – nnnnnn Feb 19 '17 at 05:47
  • @nnnnnn Yes, `eval()` is not necessary for that expected result. Destructuring assignment could be used for that purpose. "Better" is a subjective term. If OP is comfortable using `eval()`, what could be "better"? – guest271314 Feb 19 '17 at 05:48
  • @guest271314 Could you post an answer to clarify what you mean? – A. L Feb 19 '17 at 05:49
  • 1
    @guest271314 - Really? Given `name = "x"`, how do you use destructuring assignment to create a variable called `x`? – nnnnnn Feb 19 '17 at 05:50
  • @A.Lau Is requirement to assign objects to variable names `"temp0"` through and including `"temp5"`? – guest271314 Feb 19 '17 at 05:51
  • @guest271314 well mine only goes up to `temp4` but it doesn't really matter what you end up with, just make sure it's dynamic. – A. L Feb 19 '17 at 05:53
  • @guest271314 I just looked up destructuring assignment, it looks very similar to pythons tuple unpacking `a, b = (some tuple)` is that the case? – Nick is tired Feb 19 '17 at 05:56
  • 1
    @NickA Yes, but it wouldn't work in this case as they don't exist yet. So destructuring works like this `var obj = {a: "a", b: "b"}; var {a, b} = obj;` that would get you the variables. – A. L Feb 19 '17 at 06:04
  • @nnnnnn `let _name = "x"; let temp = ({[((n) => n)(_name)]:((n) => n)(_name)}); let prop = Object.keys(temp).pop(); window[prop] = temp[prop]; console.log(x)` – guest271314 Feb 19 '17 at 06:57
  • @NickA `let [a, b] = [0, 1]` – guest271314 Feb 19 '17 at 06:58

4 Answers4

2

Simply use an object:

var objects = {};

for (let i = 0; i < 5; i++)
{
    objects["temp" + i] = {};
}

Accessing with:

objects["temp0"]

or:

objects.temp0

Or if you want to pollute the global namespace you can use:

for (let i = 0; i < 5; i++)
{
    window["temp" + i] = {};
}

And access using:

temp0
temp1 //etc.

or:

window["temp0"] //just like above
Nick is tired
  • 6,860
  • 20
  • 39
  • 51
  • the `window` approach is interesting – A. L Feb 19 '17 at 05:54
  • Interestingly, I fairly recently answered a very similar question for python: http://stackoverflow.com/questions/41616703/python-declare-multiple-lists/41616755#41616755 – Nick is tired Feb 19 '17 at 06:06
2
Array(5).fill({})
// [{},{},{},{},{}]

Array(5).fill("temp").map((x, i) => x + i)
// ["temp0", "temp1", "temp2", "temp3", "temp4"] 

Array.from({length: 5}, (_, i) => "temp" + i)
// ["temp0", "temp1", "temp2", "temp3", "temp4"]

[...Array(5).keys()]
// [0, 1, 2, 3, 4]
dpren
  • 1,225
  • 12
  • 18
1

It's like this:

function makeMadObjects(num){
  var a = [];
  for(var i=0; i<num; i++){
    a.push({});
  }
  return a;
}
var arrayOfObjects = makeMadObjects(27);
arrayOfObjects[4].someProperty = 'some value';
console.log(arrayOfObjects);
StackSlave
  • 10,613
  • 2
  • 18
  • 35
1

You can use destructuring assignment to assign variable names to objects within an array, or set property names to objects within an array having dynamic .length, then retrieve specific object from array using index of object within array and property name of object where property is a plain object

let n = 5; // `n`: dynamic; e.g.; Math.floor(Math.random() * 100);
let temps = Array.from({length: n}, (_, i) => ({}));
let len = temps.length;
let [temp0, temp1, temp2, temp3, temp4 /* , ..tempN < len */ ] = temps;

console.log(temp0, temp4);

let n = 5 // Math.floor(Math.random() * 100);
let temps = Array.from({length:n}, (_, i) => ({[`temp${i}`]:{}}));
// set, get `temp0` through `tempN`, when needed for application,
// where `N` is less than `n`, e.g.; set, get `temp0`, `temp4`
let {0:{temp0}, 4:{temp4}} = temps;

console.log(temp0, temp4);
guest271314
  • 1
  • 15
  • 104
  • 177