Home > Software engineering >  Initialize state iterating an array of objects
Initialize state iterating an array of objects

Time:11-22

This questin will be more clear if i show the code:


initializing state with an empty array is easy:
export default function MyComponent() {
  const [state, setState] = useState([]);
}

however, i have an array of paths and i need to create an object for each path like this:

{
  source: path,
  options: { type: 'local' }
}

how am i supposed to initialize state with an array of objects which is created using a loop?
i tried this approach but didnt work:

export default function MyComponent({ paths }) {
  const [state, setState] = useState([ paths.map((path) => ({source: path, options: {type: 'local'} }) ]);
}

CodePudding user response:

You can try to use spread operator:

export default function MyComponent({ paths }) {
    const [state, setState] = useState([...paths.map((path) => ({source: path, options: { type: 'local' }, }))]);
}
  • Related