I've found similar but not understanding what is done wrong still. Am learning I know... I was trying to use technique like in this answer but am not sure if it is right way and can not get it to work. I get TypeError: Invalid attempt to destructure non-iterable instance.
I wish for array of string like; ['One', 'Two', 'Three']
to become object like below. Where I want to turn the array into an object with specific key that holds array of objects with those values as specific key/value object like below.
{
items: [
{
label: 'One',
id: 1
},
{
label: 'Two',
id: 2
},
{
label: 'Three',
id: 3
},
]
}
I try like
let arrayOfStrings = ['One', 'Two', 'Three']
const [label, id] = arrayOfStrings;
arrayOfStrings = [label, id];
document.write(arrayOfStrings);
Any guidance much appreciated!
CodePudding user response:
i hope I got your question correctly if your main goal is to turn something like this ['One', 'Two', 'Three'] into something like this [ { label: 'One', id: 1 }, { label: 'Two', id: 2 }, { label: 'Three', id: 3 }, ] this should be fairly easy using the .map method on the array as so
let arrayOfStrings = ['One', 'Two', 'Three']
let newArrayOfString = arrayOfStrings.map((string,stringIndex)=>{return{label:string,id:stringIndex 1}})
CodePudding user response:
Here is the code:
const input = ['One', 'Two', 'Three'];
const format = (array) => {
const items = array.map((label, index) => ({label, id: index 1}));
return {items};
};
console.log(format(input));