I want merge two separate arrays into one array of objects
const [price, setPrice] = useState([100,200,400, 700])
const [fruits, setFruits] = useState(['apple,'orange','banana','guava'])
const [sampleArray, setSampleArray] = useState([])
const mergeArray= ()=>{
setSampleArray()
}
result should be like this: console.log(sampleArray) [{fruit:'apple',price:100},{fruit:'orange',price:100,200,400},{fruit:'banana',price:400},{fruit:'guava',price:700},]
on buttonClick
<button onClick={mergeArray}>Merge Array</button>
You can do it like this:
const mergeArray = [];
for (i = 0; i < fruits.length; i++) {
mergeArray[i] = { fruit: fruits[i], price: prices[i] };
}
Here is how you can do it in one line
const [price, setPrice] = useState([100,200,400, 700])
const [fruits, setFruits] = useState(['apple','orange','banana','guava'])
const [sampleArray, setSampleArray] = useState([])
const mergeArray= ()=>{
setSampleArray(fruits.map((fr, i) => ({"fruit" : fr, "price" : price[i]})))
}
Explanation : So this will map the existing array of fruits and it will return each element as a json data with the price key that is accessed using the index. Also using maps in setState works easier with state change in react. The map will yield a array as a result and you can directly use them with the state change.
You can do this using the map function to merge 2 array columns in a single array of objects.
let array = [];
fruits.map((fruit, i) => {
let json = {
[fruit]: price[i]
}
array.push(json);
})
setSampleArray(array);