How to assign many variables to an object?
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] = ????? );
Is there any reason why you put all those values in variables in the first place, not an object right away? And why you couldn't just change your code (with search&replace) to do that?
– Bergi
Sep 18 '18 at 19:04
2 Answers
2
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)
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)
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Just use shorthand properties
– Bergi
Sep 18 '18 at 19:03