0

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!

1
  • You could do this, but it depends on your actual requirement. How do we know that the id for "One" should be 1? Is it because you are starting with 1 and counting up (as opposed to a 0 index), or is it because the string "One" is an English word corresponding to the number 1? Or some other reason? It would be helpful if you explicitly lay out your needs. Commented Jun 21, 2022 at 20:21

2 Answers 2

1

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}})
Sign up to request clarification or add additional context in comments.

Comments

0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.