Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript – Extract items from array and add with a new key to a new array of a specific length

I have an array of images:

const imageArray = Object.entries(profileData.images)

//imageArray  = ["0": "http://imagelink1", "1" : "http://imagelink2"]

I am setting an initial state of images array to

  const [imageUrl, setImageUrl] = useState([
    { image: '' },
    { image: '' },
    { image: '' },
    { image: '' },
    { image: '' },
    { image: '' },
  ])

Expected initial state is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  const [imageUrl, setImageUrl] = useState([
    { image: 'http://imagelink1' },
    { image: 'http://imagelink2' },
    { image: '' },
    { image: '' },
    { image: '' },
    { image: '' },
  ])

How to get values from first array and construct this new array of length 6?

>Solution :

You can create a new array with Array.from(), and then use the index from your array that you’re creating to grab the image from imageArray. If the index doesn’t exist in your imageArray you can take a default of "" using the nullish coalescing ?? operator:

const [imageUrl, setImageUrl] = useState(() => 
  Array.from({length: 6}, (_, i) => ({image: imageArray[i] ?? ""}))
)

Above I’m passing a function into useState() so that the array is only constructed on the initial mount of your component and not on every rerender (it’s useless after the first render anyway, so no need to reconstruct it)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading