Reputation: 976
How can I achieve this without hardcoding the index?
const { TargetQuantity: targetQuantity1 } = res.data.d.results[0]
const { TargetQuantity: targetQuantity2 } = res.data.d.results[1]
const { TargetQuantity: targetQuantity3 } = res.data.d.results[2]
const { TargetQuantity: targetQuantity4 } = res.data.d.results[3]
Upvotes: 0
Views: 180
Reputation: 1508
try this:
const results = [
{ TargetQuantity: 1 },
{ TargetQuantity: 2 },
{ TargetQuantity: 3 },
{ TargetQuantity: 4 }
];
results.map((item, i) => {
let str ="TargetQuantity"+ (i+1) +" = item.TargetQuantity";
eval(str)
});
This will create global variables TargetQuantity1,TargetQuantity2, TargetQuantity3 ...
and so on
Upvotes: 1
Reputation: 1601
const results = [
{TargetQuantity: 1},
{TargetQuantity: 2},
{TargetQuantity: 3},
{TargetQuantity: 4}
];
(function (context){
for(let i = 0; i < results.length; i++){
context[`targetQuantity${i+1}`] = results[i].TargetQuantity;
}
})(this);
console.log(targetQuantity3);
But why would you wanna do that?
Upvotes: 0