我正在尝试创建以下内容:
我有一个包含 n 个项目的数组,随着添加更多项目,我希望将它们分配给每个对象,但要考虑每个对象中分配的百分比。
const items = []
const obj1 = {id: 1, allocationPercentage: 40, items: []}
const obj2 = {id: 2, allocationPercentage: 20, items: []}
const obj3 = {id: 3, allocationPercentage: 40, items: []}
如果我向数组添加 5 个项目,那么它看起来会像这样:
const items = ["item1", "item2", "item3", "item4", "item5"]
const obj1 = {id: 1, allocationPercentage: 40, items: ["item1", "item2"]}
const obj2 = {id: 2, allocationPercentage: 20, items: ["item3"]}
const obj3 = {id: 3, allocationPercentage: 40, items: ["item4", "item5"]}
每个对象中的分配百分比可能会有所不同。
最佳答案
const items = ["item1", "item2", "item3", "item4", "item5"]
const obj1 = {id: 1, allocationPercentage: 40, items: []}
const obj2 = {id: 2, allocationPercentage: 20, items: []}
const obj3 = {id: 3, allocationPercentage: 40, items: []}
// group objs in an array
const objs = [obj1, obj2, obj3]
let cursor = 0
for (const obj of objs) {
// calculate number of items to add to the array per object
const numberOfItems = Math.floor(obj.allocationPercentage / 100 * items.length)
// get the items
const itemsToAdd = items.slice(cursor, cursor + numberOfItems)
// push them to the items
obj.items.push(itemsToAdd)
// remember to move the cursor
cursor += numberOfItems
}
console.log(objs)
关于javascript - 如何根据每个对象的分配百分比将项目分配给对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77298144/