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] = ????? );






Just use shorthand properties

– Bergi
Sep 18 '18 at 19:03






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

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)