burrito
burrito

Reputation: 154

How i can save an object with more elegant way

I have an object:

var parementro = {
  myparam:{
    param:"\n ..",
    param1:"\n ..",
    param2: "\n ..",
    param3: "\n ..",
    param4: "\n \t ..",
    param5: "\n \t ..",
    param7: "\n \t .."
  },
  endparams:{
    param: "stop"   
  }
};

Inside the variables param,param1... there are strings and I want to write a text with this param,param1,.... The object

 paramentro.myparam 

has more params than seven. How do I save these strings without writing continuously param8,param9 etc. This object is static, it does not change dynamically and this is the reason I created the object like this.

Upvotes: 1

Views: 115

Answers (4)

rockTheWorld
rockTheWorld

Reputation: 501

You can use Object.values for this purposes:

let parementro = {
  myparam:{
    param:"\n ..",
    param1:"\n ..",
    param2: "\n ..",
    param3: "\n ..",
    param4: "\n \t ..",
    param5: "\n \t ..",
    param7: "\n \t .."
  },
  endparams:{
    param: "stop"   
  }
};

Object.values(parementro.myparam).join(',')

Upvotes: 0

Elena
Elena

Reputation: 163

If you want to use an object

var parementro = {
  myparam:{
    param:"\n ..",
    param1:"\n ..",
    param2: "\n ..",
    param3: "\n ..",
    param4: "\n \t ..",
    param5: "\n \t ..",
    param7: "\n \t .."
  },
  endparams:{
    param: "stop"   
  }
};

const obj = {...parementro.myparam}
console.log(obj)

if you want to use array

var parementro = {
  myparam:{
    param:"\n ..",
    param1:"\n ..",
    param2: "\n ..",
    param3: "\n ..",
    param4: "\n \t ..",
    param5: "\n \t ..",
    param7: "\n \t .."
  },
  endparams:{
    param: "stop"   
  }
};

const obj1 = {...parementro.myparam}
const obj = Object.values(obj1)
console.log(obj)

Upvotes: 0

Nikita
Nikita

Reputation: 36

You can use something like this

x - (amount of params -1)

for(let i=0; i<=x; i+=1){
parementro.myparam = { ...parementro.myparam, [(i>0) ? `param${i}`: 'param']:'\n'}
}

Upvotes: 0

JG3
JG3

Reputation: 130

As another comment suggests you could use an Array since your keys are just incrementing each time. Then you can use various methods to populate or manipulate the array and it's contents. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Instance_methods

But, if you do want to use an Object, you could use an array to assign keys & values to your object in a variety of ways. (this below uses ES6 and could be modified to populate an array, too)

const anObject = {};

Array.from(new Array(5)).map((each, index) => anObject[`param${index}`] = "my string");

https://jsbin.com/baqaxocosa/edit?js,console

Upvotes: 1

Related Questions