简体   繁体   中英

Push Array values with a dynamic keyname in javascript

I am using a function to push values to an array with two parameters.In this the second parameter indicates the level of arrays.so i need to push values to that array using this level params value.

Here is my code:

addLevel1(i, level) {
        let advArr1                                 =   {};
        let nextLevel                               =   parseInt(level)+1
        advArr1["level"+level+"_adv_url"]           =   "";
        advArr1["level"+level+"_custom_variables"]  =   "";
        advArr1["level"+level+"_percentage"]        =   "";
        advArr1["level"+level+"_status"]            =   "";
        advArr1["level"+nextLevel]                  =   [];
        this.containers[i].level1.push(advArr1);
        console.log(this.containers);
};

In this instread of

this.containers[i].level1.push(advArr1);

I need dynamic vale for level1. ie if param level is 1 it should be

this.containers[i].level1.push(advArr1);

and if param level is 2 it will be

this.containers[i].level2.push(advArr1);

The sense of objects is that you can easily look up properties by name . As you mix in the dynamic level variable into it, you defeat that purpose:

  const levels = [
   { level1_status: "ok" },
   { level2_status: "wrong" }
 ];

 for(const level of levels) {
   // How to get the status here?
   level["level" + /*How to get the level?*/ "_status"]
 }

Now instead, you should have static keys, so all levels should have the same keys. To differentiate different levels, you could use a level property :

  const levels = [
   { level: 1, status: "ok" },
   { level: 2, status: "wrong" }
  ];

  for(const level of levels) {
    console.log("Level:", level.level); // isn't that simple?

    console.log("has Status:", level.status); // Wohoo!
  }

Now the next thing is that containers[i].level1 thing: If you would have a levels array property on the container, you could just access it as containers[i].levels[1] without any problems. The main benefit is, that you can now go easily over the different levels of a container: for(const level of container.levels) .

Under the assumption that the container has such an array, your code could be:

 addLevel(i, level){
    this.containers[i].levels[level] = {
      level,
      nextLevel: level + 1,
      advUrl: "",
      percentage: 0, // does make more sense than a string, right?
       status: "",
   };
 }

 // somewhere:
 context.addLevel(/*i*/ 0, /*level*/ 1);

您可以使用方括号而不是点符号来访问对象属性

this.containers[i][level].push(advArr1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM