我正在尝试从另一个对象数组构建一个对象数组:
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: a.i });
a.i += v.size.height;
return a;
}, { res: [], i: 0 } ).res;
console.log(JSON.stringify(result));
我简单地使用一个对象作为reduce
的初始化器,它有两个属性:res
,这是我们想要得到的结果数组,和i
是 top
的累加。
当最后返回对象时,我只是得到它的 res
属性。
关于javascript - 创建一个基于先前值的新对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49041112/