I have an object, I'm trying to convert it to an array first and loop through the array and print it in the console but still, it does not destruct the array, it gives me an object.
const person = [
{
firstName : 'John',
age : '24'
}
];
const btn = document.createElement('button');
btn.innerText = 'Click';
document.body.appendChild(btn);
btn.addEventListener('click', ()=>{
let newarray = Object.entries(person);
newarray = person.map((get)=>{
const {firstName, age} = get;
return {firstName, age};
});
console.log(newarray);
});```
CodePudding user response:
If you want nested array in your newArray then do the following:
newarray = person.map((get)=>{
const {firstName, age} = get;
return [firstName, age];
});
CodePudding user response:
What do you mean by you are trying to convert it to an array? To get the key values you can use Object.keys or for values you can use Object.values.
CodePudding user response:
Some points to clarify:
Variable const person = [{}]
would be better named as persons
, as an array of multiple persons, to avoid confusion to others. Also get
variable in map would be better as person
or per
or p
.
Immediate assignment without using the variable is useless:
let newarray = Object.entries(person); // useless assignment
newarray = person.map(...);
You need to clearly indicate what is your Input object, and how you expect your Output Array to be like.
I'm thinking that your input is Array of Object, and you want an Array of Array of Values in orders like:
// output
[ ['John', 24], ['Bob', 25], ['Carl', 23] ]
If it's the case, then you can use Object.values
to convert object into Array of values:
const persons = [
{
firstName : 'John',
age : 24
}
];
const btn = document.createElement('button');
btn.innerText = 'Click';
document.body.appendChild(btn);
btn.addEventListener('click', () => {
let newarray = persons.map((person) => {
return Object.values(person);
});
console.log(newarray); // [ ['John', 24] ]
});