0

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] = ????? );
Travis Heeter
  • 13,002
  • 13
  • 87
  • 129
  • Just use [shorthand properties](https://stackoverflow.com/questions/34414766/javascript-object-literal-what-exactly-is-a-b-c) – 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 Answers2

1

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)
Mark
  • 90,562
  • 7
  • 108
  • 148
0

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)
michaelitoh
  • 2,317
  • 14
  • 26