简体   繁体   中英

Create Array by Dynamic Keys and Values

I am getting a value in string in a variable, ie

let name = 'Vishesh';
let name2 = 'Vishesh2';

and an Array ie

let cars = [{carName: "Mercedes"},{carName: "Volvo"},{carName:"BMW"}];

Now I want to create an Array where my Key is the name and in value, there should be cars array, ie

Array=[{Vishesh: [{carName: "Mercedes"},{carName: "Volvo"},{carName:"BMW"}]},{Vishesh2: [{carName: "Mercedes"},{carName: "Volvo"},{carName:"BMW"}]}];
let name = 'Vishesh';
let name2 = 'Vishesh2';
let cars = [{carName: "Mercedes"},{carName: "Volvo"},{carName:"BMW"}];
let array = []

array.push({[name]:cars})
array.push({[name2]:cars})
console.log(array);

You can interpolate the names directly into the dictionary construction as a key.

 let name = 'Vishesh'; let name2 = 'Vishesh2'; console.log([ { [name]: [ { carName: "Mercedes" }, { carName: "Volvo" }, { carName:"BMW" } ] }, { [name2]: [ { carName: "Mercedes" }, { carName: "Volvo" }, { carName:"BMW" } ] } ]); 

But you can do this a bit more dynamically

 let name = 'Vishesh'; let name2 = 'Vishesh2'; let cars = [ { carName: "Mercedes" }, { carName: "Volvo" }, { carName:"BMW" } ]; function keyByNames(names, cars) { let named = {} names.forEach(name => { named[name] = JSON.parse(JSON.stringify(cars)) }) return named } console.log(keyByNames([ name, name2 ], cars)); 

How about this (assuming it is only two names):

let obj1 = {};
obj1[name] = cars;

let obj2 = {};
obj2[name2] = cars;

var array = [obj1, obj2];

Do note: both objects reference the same array. Changing the array will therefore 'update' the array in two places (since it is by reference).

If however you want a dynamic set of names your code could look like this:

var names = ["Vishesh", "Vishesh2", "Vishesh3"];

var array = [];
for(var i = 0; i < names.length; i++) {
    var name = names[i];

    var obj = {};
    obj[name] = cars;

    array.push(obj);
}

using reduce function on your array of cars can be solution as well.:

 let names = ["Wishes1", "Wishes2", "Wishes3"] let cars = [{carName: "Mercedes"},{carName: "Volvo"},{carName:"BMW"}]; const withNames = (names) => (currentMapState, currentItem, currentIndex) => { currentMapState[names[currentIndex]] = currentItem; return currentMapState; } console.log(cars.reduce(withNames(names), {})); 

And bonus is that withNames function is easily testable. Have a nice day.

if there is always two names:

const Array = [
  { [name]: cars },
  { [name2]: cars }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM