0

Wondering if it is possible to use a loop to add dynamically named objects to an array, so I don't need to repeat the "push" on an array. Tks !!

  let _objA0 = { "name":"regionId", "value":"myRegion" };
  let _objA1 = { "name":"vdcId", "value":"myId" };
  let _objA2 ... _objA100
  
  let test = []
  test.push(_objA0)
  test.push(_objA1)
  ...
  test.push(_objA100)
5
  • do you have 100 variables of objects ? Commented Nov 24, 2020 at 3:26
  • 2
    If it's a matter of not repeating the push you can just do let test = [_objA0, _objA1, ..., _objA100]; The real question though, is why you need to have these dynamically named objects to begin with. Commented Nov 24, 2020 at 3:26
  • Please show us how those objects are being created. Commented Nov 24, 2020 at 3:29
  • Tks, we have a "JSON template based" creation flow, where the JSON contains dozens of product attributes. One of the attribute contains an array of objects with dozens of configurations. I need to populate the array with my "prepared objects", and I wish to find something decent. Commented Nov 24, 2020 at 3:32
  • I have to admit it's a lame ad hoc design in my team and I have little to do to change the design from ground up... Commented Nov 24, 2020 at 3:48

2 Answers 2

1

I guess it's the right time to use eval

let test = [];
for(let i = 0; i <= 100; i++) {
  test.push(eval(`_objA${i}`));
}
Sign up to request clarification or add additional context in comments.

3 Comments

Is it ever the right time to use eval? I mean, it's all fun and games until someone pushes an XSS exploit into one of your objects... (Not my downvote, btw)
@RobbyCornelissen The only dynamic variable in this eval is i from the loop, and it's getting the value of a variable, nothing to inject with, which is relatively safe in this case. Although it's discouraged to use it.
its also fun and games until someone decided they will write down all the variables one by one, and decide to convert it to an array. lol, I guess its not a bad time to use eval. I will give u a up.
0

You can access variables (with var keyword) by window object , try this:

var _objA0 = { "name":"regionId", "value":"myRegion" };
var _objA1 = { "name":"vdcId", "value":"myId" };

let test = [];

for(let i = 0; i < 2; i++){
    test.push(window['_objA' + i]);
}

console.log(test)

2 Comments

Well, if he can change the let to var in the generating phase, I would suggest just generate an array in the first place...
This also assumes that the code is executed in a browser context, which is not necessarily a given.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.