i have a List of objects here
const List_objects = [
{
Product = A,
Price = 20
},
{
Product = B,
Price = 21
}
]
and I have a person_data with
const [person_data,setPerson_Data] = useState({
Product : 0,
Price = :0
})
and i have a onClick function here
const handleClick = e => {
setPerson_Data({
Product: String(List_objects.map(e=>e.Product)),
Price : String(List_objects.map(e=>e.Price))
})
and when I print via console.log this will be the result
{
Product: A,B,
Price : 20,21
}
and I wanted to do it in reverse
from these
{
Product: A,B,
Price : 20,21
}
into these
[
{
Product = A,
Price = 20
},
{
Product = B,
Price = 21
}
]
I am 3rd yr ComEng student and i am developing a Online Inventory System using React JS it will really a great help in my school specially my career as aspirant developer
do you guys any idea how to execute it ? or maybe some alternative also it will help if there is sample code
THANK YOU IN ADVANCE!
>Solution :
Here are two possible ways go create the array from it. One uses a Generator, the other uses map().
const input = {
Product: "A,B",
Price: "20,21",
};
function* fromObjectGenerator(obj) {
const products = obj.Product.split(",");
const prices = obj.Price.split(",");
for (let i = 0; i < products.length; i++) {
yield {
Product: products[i],
Price: prices[i],
};
}
}
function fromObject(obj) {
const products = obj.Product.split(",");
const prices = obj.Price.split(",");
return [...Array(products.length)].map((_, idx) => ({
Product: products[idx],
Price: prices[idx],
}));
}
console.log([...fromObjectGenerator(input)]);
console.log(fromObject(input));
Please note: Both implementations assume that the number of
productsmatches the number ofpricesbut which little adjustments it could also work if that was not the case.