[英]Create a new array of objects building on previous values
我正在尝试从另一个对象数组中构建一个对象数组:
const items = [
{
id: 'thing-1',
size: {
height: 50
},
},
{
id: 'thing-2',
size: {
height: 100
}
},
{
id: 'thing-3',
size: {
height: 500
}
},
{
id: 'thing-4',
size: {
height: 200
}
}
];
这是我的预期结果:
const newList = [
{id: 'thing-1', top: 0},
{id: 'thing-2', top: 50},
{id: 'thing-3', top: 150},
{id: 'thing-4', top: 650},
];
基本上,如果所有项目都堆叠在一起,我会尝试找到顶部位置。 在构建新列表时,它会计算每个项目的顶部位置(相对于项目堆栈)。 因此,如果第一个项目位于堆栈的顶部(从顶部开始为 0)并且高 50,则第二个项目从顶部开始为 50。 最后一项的高度无关紧要。
我有一种感觉,可以在这种情况下使用 reduce,但我不确定如何在这种情况下形成语法。
我尝试过这样的事情,但不太正确。 此外,如果我能做到这一点,而无需在 reduce 的范围之外创建一个空数组,那将是可取的。
const itemsReduced = [];
items.reduce((acc, elm) => {
itemsReduced.push({id: elm.id, top: acc + elm.size.height});
return elm.size.height;
});
console.log(itemsReduced);
试过了,但它只是导致了这个。
[
{id: "thing-2", top: "[object Object]100"},
{id: "thing-3", top: 600},
{id: "thing-4", top: 700},
]
我正在考虑一个基本循环,但它在迭代时仍然需要项目的上下文。
这是一个使用reduce
的简单解决方案
const items = [{id: 'thing-1', size: {height: 50}}, {id: 'thing-2', size: {height: 100}}, {id: 'thing-3', size: {height: 500}}, {id: 'thing-4', size: {height: 200}} ]; var result = items.reduce((a, v) => { a.res.push({ id: v.id, top: ai }); ai += v.size.height; return a; }, { res: [], i: 0 } ).res; console.log(JSON.stringify(result));
我只是使用一个对象作为reduce
的初始化器,它有两个属性: res
是我们想要得到的结果数组,而i
是top
s 的累加。
当对象最后返回时,我只是获取它的res
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.