我正在使用 React Js,我有一个对象列表,第一个对象有一个与第二个对象相同的数组元素
Im using react Js, I have a list of Objects, the first object has a elements of array same thing with second Object
我这里有一个对象列表
const List_objects = [
{
Product = A,
Price = 20
},
{
Product = B,
Price = 21
}
]
我有一个 person_data 和
const [person_data,setPerson_Data] = useState({
Product : 0,
Price = :0
})
我这里有一个 onClick 函数
const handleClick = e => {
setPerson_Data({
Product: String(List_objects.map(e=>e.Product)),
Price : String(List_objects.map(e=>e.Price))
})
当我通过 console.log 打印时,这将是结果
{
Product: A,B,
Price : 20,21
}
我想反过来做
来自这些
{
Product: A,B,
Price : 20,21
}
进入这些
[
{
Product = A,
Price = 20
},
{
Product = B,
Price = 21
}
]
我是 ComEng 三年级学生,我正在使用 React JS 开发一个在线库存系统,这对我的学校非常有帮助,特别是我作为有抱负的开发人员的职业
你们知道如何执行吗?或者如果有示例代码
也可能有一些替代方法
提前致谢!
这里有两种从中创建数组的可能方法。一个使用 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 products
matches the number of prices
but which little adjustments it could also work if that was not the case.
我这里有一个对象列表
const List_objects = [
{
Product = A,
Price = 20
},
{
Product = B,
Price = 21
}
]
我有一个 person_data 和
const [person_data,setPerson_Data] = useState({
Product : 0,
Price = :0
})
我这里有一个 onClick 函数
const handleClick = e => {
setPerson_Data({
Product: String(List_objects.map(e=>e.Product)),
Price : String(List_objects.map(e=>e.Price))
})
当我通过 console.log 打印时,这将是结果
{
Product: A,B,
Price : 20,21
}
我想反过来做
来自这些
{
Product: A,B,
Price : 20,21
}
进入这些
[
{
Product = A,
Price = 20
},
{
Product = B,
Price = 21
}
]
我是 ComEng 三年级学生,我正在使用 React JS 开发一个在线库存系统,这对我的学校非常有帮助,特别是我作为有抱负的开发人员的职业
你们知道如何执行吗?或者如果有示例代码
也可能有一些替代方法提前致谢!
这里有两种从中创建数组的可能方法。一个使用 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
products
matches the number ofprices
but which little adjustments it could also work if that was not the case.