我正在开发节点js应用程序,我面临的问题是必须在数组中添加位置点,但是每个位置点是不同的,比如第一个数组/对象需要10个,然后下一个数组/对象必须是7个。
let converter = [
{ name: 'team-1', killPoint: 8 },
{ name: 'team-2', killPoint: 7 },
{ name: 'team-7', killPoint: 56 },
{ name: 'team-9', killPoint: 68 }
]
const pointsystem = [10, 7, 6, 5, 4, 3, 2, 1, 0];
const positionAdd = (objects) => {
let i = 0
const posRes = {};
objects.forEach(({
name,
killPoint
}) => {
posRes[name] = posRes[name] || {
name,
positionPoint: 0,
killPoint: 0,
};
posRes[name].positionPoint = pointsystem[i+1];
posRes[name].killPoint = killPoint;
});
return Object.values(posRes);
};
console.log(positionAdd(converter));
尝试使用这段代码,但它的工作不像需要的那样
输出不足
[
{ name: 'team-1', positionPoint: 10, killPoint: 8 },
{ name: 'team-2', positionPoint: 7, killPoint: 7 },
{ name: 'team-7', positionPoint: 6, killPoint: 56 },
{ name: 'team-9', positionPoint: 5, killPoint: 68 }
]如果有更多的队伍,那么点应该持续到0.
发布于 2022-08-31 17:54:29
使用map()而不是附加到结果数组。
使用回调函数的第二个参数获取数组索引,并使用该参数对pointsystem进行索引。
使用对象扩展语法将其合并到来自converter的对象中。
let converter = [
{ name: 'team-1', killPoint: 8 },
{ name: 'team-2', killPoint: 7 },
{ name: 'team-7', killPoint: 56 },
{ name: 'team-9', killPoint: 68 }
]
const pointsystem = [10, 7, 6, 5, 4, 3, 2, 1, 0];
const positionAdd = (objects) => objects.map((obj, i) => ({...obj, positionPoint: pointsystem[i]}));
console.log(positionAdd(converter));
发布于 2022-08-31 17:56:59
以下内容还将更改原始对象。我不知道OP的目的是:
const data = [
{ name: 'team-1', killPoint: 8 },
{ name: 'team-2', killPoint: 7 },
{ name: 'team-7', killPoint: 56 },
{ name: 'team-9', killPoint: 68 }
],points = [10,7,6,5,4,3,2,1,0];
console.log(data.map((d,i)=>{
d.positionPoint=points[i]??0;
return d;
}));
发布于 2022-08-31 17:53:57
您正在向变量i中添加1,而不是在每个循环之后实现i。每次迭代后,您需要将i增加1。
示例:
posRes[name].positionPoint = pointsystem[i];
i += 1;测试:
let converter = [
{ name: 'team-1', killPoint: 8 },
{ name: 'team-2', killPoint: 7 },
{ name: 'team-7', killPoint: 56 },
{ name: 'team-9', killPoint: 68 }
]
const pointsystem = [10, 7, 6, 5, 4, 3, 2, 1, 0];
const positionAdd = (objects) => {
let i = 0
const posRes = {};
objects.forEach(({
name,
killPoint
}) => {
posRes[name] = posRes[name] || {
name,
positionPoint: 0,
killPoint: 0,
};
posRes[name].positionPoint = pointsystem[i];
i += 1;
posRes[name].killPoint = killPoint;
});
return Object.values(posRes);
};
console.log(positionAdd(converter));
https://stackoverflow.com/questions/73559790
复制相似问题