1

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.

Alexandro Pineda
  • 706
  • 3
  • 10
  • Does this answer your question? [How do I loop through or enumerate a JavaScript object?](https://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) – kmoser Sep 19 '21 at 02:44

4 Answers4

1

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] })
}
Erick Silva
  • 338
  • 1
  • 5
0
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" }
*/
kmoser
  • 8,780
  • 3
  • 24
  • 40
0

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);
kiranvj
  • 32,342
  • 7
  • 71
  • 76
0
              const myFunc = (obj) => {
                   const years = Object.keys(obj).map((c, i) => {
                   const values = Object.values(obj).map((b) => b);

                    return { edad_beneficiario: values[i] };
                        });
                     console.log(years);
                 };

you can actually make it a lot shorter but i just wanted you to know that you can access object keys as well .