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

How can I pass array values to a property of Object?

I have two arrays(word and translatedWord). They contain words(word array contains words in english and translatedWord contains the same words but in another language ). I want to create an array of objects, each object to have the properties value, translation and id. I solved how I can create an object with the translatedWord properties, but I don’t know how can I add the word values.
I want something like:

[
   {
      value:word[0],
      translation:translatedWord[0]
   },
   {
      value:word[1],
      translation:translatedWord[1]
   }
]

Arrays:

const word=['table','chair','bottle']
const translatedWord=['masa','scaun','sticla']

My object

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 [object, setObject]=React.useState({
    value:'',
    translation:'',
    id: nanoid(),
    isFavorite:false
  })

My idea is to create two functions like this:

Function for populate the object with translated property:

 function addTranslateToObject(){
    setObject(prevValue=>translatedWord.map(data=>({
       ...prevValue,
       translation:data
    })))

Function for populate the object with value property:

function addValue(){
    setObject(prevValue=>prevValue.map(data=>(
      {
      ...data,
      value:word[index]   //the problem is: I don't know how to increment the index value
    }))
    )
  }

>Solution :

From my POV, the useState looks like this:

const [object, setObject] = React.useState([])

While in the setObject, I’d pass in the words array ( that contains the values) mapped into a new array with the desired object.

setObject(words.map((word, index) => {
    return {
       id: index, 
       value: word,
       translation: translatedWord[index],
       isFavorite: false 
    }
 })

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