Home > Software engineering >  javascript - Extract items from array and add with a new key to a new array of a specific length
javascript - Extract items from array and add with a new key to a new array of a specific length

Time:11-19

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

  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?

CodePudding user response:

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)

CodePudding user response:

So you can use Array constructor with n number of elements, and use fill to fill the items with a value, and then map with each item with its' corresponding index in imageArray

  const [imageUrl, setImageUrl] = useState(Array(6).fill(undefined).map((item, index) => ({ image: imageArray[index] ?? '' })))
  • Related