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!
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 })));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With