简体   繁体   中英

Form array to object in Javascript

I have this array and a variable:

const a = [1, 5, 3]
const model = 'Audi'

I want on object like that:

const obj = {
    data: {
      0: 1,
      1: 5,
      2: 3,
    },
    cars: {
      0: 'Audi',
      1: 'Audi',
      2: 'Audi',
    },
  }

I can I do that?

I think I can use a for. This is what I think to do:

const obj = {}
for(let i = 0; i < a.lenght; i++) {
  obj.cars = 
}

I don't know ho to complete the code... and I don't think is the best solution.

Thanks

You could use Object.assign with spread syntax and map method.

 const a = [1, 5, 3] const model = 'Audi' const obj = { data: Object.assign({}, ...a.map((e, i) => ({[i]: e}))), cars: Object.assign({}, ...a.map((e, i) => ({[i]: model}))) } console.log(obj) 

In addition to the other answers, a different approach could be with reduce and comma expression.

 const a = [1, 5, 3]; const model = 'Audi'; const create = (arr, model) => arr.reduce((acc, val, i) => // comma expression which evaluates from left to right and returns the last value (acc.data[i] = val, acc.model[i] = model, acc), { data: {}, model: {}}); console.log(create(a, model)); 

 const myArray = [1, 5, 3];
 const model = 'Audi';
 var obj = {};
 obj.data = {};
 obj.cars = {};
 var i = 0;
myArray.forEach(function(element){
i++;
obj.data[i] = element; 
obj.cars[i] = model;

})

You could take two different variables which are later properties of the wanted object and use the array for assigning to an object and map model to an array and assign this to an object.

Both assignings keeps the indices as keys for the new object.

 var a = [1, 5, 3], model = 'Audi', data = Object.assign({}, a), cars = Object.assign({}, a.map(_ => model)), result = { data, cars }; console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

You could do a loop to set new const "final" (primitive way) But I think @nenad's version is better.

 const a = [1, 5, 3]; const model = 'Audi'; const final = {}; var cars = [], data = []; for(var i=0; i<a.length;i++) { data.push(i); cars.push(model); } final.data = data; final.cars = cars; console.log(final); 

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