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
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
}
})