Travis Heeter
Travis Heeter

Reputation: 14054

How to assign many variables to an object?

I have a lot of variables that are already defined:

var listOfCars = $('#cars');
var car        = $('#currentCar');
var carIndex   = $(car).index();
var isFirstCar = carIndex == 0;
var isLastCar  = carIndex == $(listOfCars).length - 1;
// and many more in real life

And I want to put all of them into an object where the name of the variable is also the name of the key. This is how I would do it if I wanted to rewrite every line:

var params = {
  listOfCars : listOfCars,
  car        : car,
  ...
};

With Sublime I was able to create an array of variable names:

var paramKeys = [ "listOfCars", "car", "carIndex"...];

But I'm stuck on how to assign the actual values easily. I'm hoping to find a one-liner. Something like this:

paramKeys.every( key => param[key] = ????? );

Upvotes: 0

Views: 38

Answers (2)

michaelitoh
michaelitoh

Reputation: 2340

Personally I thing it's easier for you to use Property Shorthand:

var listOfCars = [];
var car = "car info";
var params = { listOfCars, car }; 

console.log(params)

Upvotes: 0

Mark
Mark

Reputation: 92440

You can do almost the same thing as your array notation by swiping out the brackets for curly braces. This will use the names of the variables as keys and the values as values:

var listOfCars = ["list of cars"]
var car        = "a car"
var carIndex   = 26
var isFirstCar = 0
var isLastCar  = 10

let obj = {listOfCars, car, carIndex, isFirstCar, isLastCar }
console.log(obj)

Upvotes: 1

Related Questions