Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop in const object

I am trying to do the following:

const obj {
    for(i=0;i<data.length;i++){
       Key[i]: data[i].description
    }
}

(I know I probably also needs to add a comma at the end of each line except on the last one, but I already get errors in the earlier stage)

This doesn't seem to be allowed in JS. Are there any alternatives? Thank you!

like image 478
user3339208 Avatar asked Sep 18 '26 13:09

user3339208


2 Answers

You could use Object.assign in combination with spread syntax ... and map the single objects with Array#map and use computed property names for the object.

const obj = Object.assign(...data.map((o, i) => ({ ['Key' + i]: o.description })));
like image 123
Nina Scholz Avatar answered Sep 20 '26 02:09

Nina Scholz


It looks like you're trying to create an object from a keys array and a data array.

A clean approach would be to use array reduction:

const obj = data.reduce((obj, d, i) => {
  obj[Key[i]] = d.description;
  return obj;
}, {});

which, assuming your environment allows it, can be simplified further (due note that this will be cleaner code but less efficient because the object spread copies the entire object every time):

const obj = data.reduce((obj, d, i) => ({
  ...obj,
  [Key[i]]: d.description
}), {});

but you could also use a simple for loop:

const obj = {};
for (let i = 0; i < data.length; i++) {
  obj[Key[i]] = data[i].description;
}

Note: The code above will break if Key.length !== data.length.

like image 45
nem035 Avatar answered Sep 20 '26 01:09

nem035