I have this in my code:
let obj = {EdadBeneficiario1: '32', EdadBeneficiario2: '5'}
var years = [];
let i;
for (i= obj;i<=obj;i++)
{
years.push({ edad_beneficiario : i })
}
the output is
[
edad_beneficiario:{EdadBeneficiario1:"32", EdadBeneficiario2:"5"}
]
but what i want is this
[
{edad_beneficiario:"32"},
{edad_beneficiario:"5"}
]
what can i do?
EDIT
By the way, if i do this
years.push({ edad_beneficiario :obj.EdadBeneficiario1})
years.push({ edad_beneficiario :obj.EdadBeneficiario2})
the output what i want resolve but i want it to do it with a for loop. Please, Help.
The problem is that in the loop, you are setting i = obj, then i = {EdadBeneficiario1: '32', EdadBeneficiario2: '5'}. i must be a integer value to work with the for loop in this case. You can use Object.values method to transform obj values into an array and get it's data to use it in the for loop.
let obj = {EdadBeneficiario1: '32', EdadBeneficiario2: '5'}
var years = [];
let objValuesArray = Object.values(obj);
for (let i = 0; i < objValuesArray.length; i++) {
years.push({ edad_beneficiario : objValuesArray[i] })
}
let obj = {EdadBeneficiario1: '32', EdadBeneficiario2: '5'}
var years = [];
Object.entries(obj).map(([key, value]) => {
years.push( {edad_beneficiario: value} )
}
)
console.log(years)
/*
Array [ {…}, {…} ]
0: Object { edad_beneficiario: "32" }
1: Object { edad_beneficiario: "5" }
*/
Does this work for you? Use Object.values() and Array.map() to get the desired output.
let obj = {
EdadBeneficiario1: '32',
EdadBeneficiario2: '5'
}
const output = Object.values(obj).map(value => ({
edad_beneficiario: value
}));
console.log(output);