Home > Mobile >  React JS how to copy array into object/dictionary array
React JS how to copy array into object/dictionary array

Time:11-27

I have the below list represents images sources coming from Flask backend,

[
   "www.example.com","www.example2.com","www.example3.com"...
]

Now I'm trying to use the react react-image-gallery to display all those images. From the tutorial I see I need to make it like below:

const images = [
  {
    original: "www.example.com",
    thumbnail: "www.example.com/thumbnail",
  }
]

I'm confused about how to make the array list of images URLs mapped into this object/dictionary array? Ideally I need to make it like:

const images = [
  {
    original: "www.example.com",
    thumbnail: "www.example.com/thumbnail",
  },
  {
    original: "www.example2.com",
    thumbnail: "www.example2.com/thumbnail",
  },
  {
    original: "www.example3.com",
    thumbnail: "www.example3.com/thumbnail",
  }......
]

Could anyone please enlighten me? Any help will be much appreciated!

CodePudding user response:

You can map over source array as:

const srcArr = ["www.example.com", "www.example2.com", "www.example3.com"]

const result = srcArr.map(original => ({ original, thumbnail: `${original}/thumbnail`}));
console.log(result)

CodePudding user response:

Just use map

const list = [
   "www.example.com","www.example2.com","www.example3.com",
  
]

const result = list.map(item => {
  return {
     original: item,
     thumbnail: `${item}/thumbnail`,
  }
})

console.log(result)

CodePudding user response:

Array.prototype.map() is a good choice.

Maybe you should learn some prototype methods of Array here.

  • Related