我有一个对象,我想循环并返回数组中每个键的累积长度。以下是对象和理想的输出:
const books = {
"book_1": ["image-1", "image-2", "image-3"], // 3
"book_2": ["image-1"], // 1
"book_3": ["image-1", "image-2"] // 2
}
// Ideal Output
[3, 4, 6]
我知道不可能遍历对象,但是我先使用Object.key()
然后使用.reduce()
来获取每个键的长度,但我只是想不出如何分割它们一起。任何帮助将不胜感激
const books = {
"book_1": ["image-1", "image-2", "image-3"], // 3
"book_2": ["image-1"], // 1
"book_3": ["image-1", "image-2"] // 2
}
console.log(Object.keys(books).reduce(function (accumulator, currentValue, index) {
console.log(books[Object.keys(books)[index]].length)
return currentValue;
}, []))
答案 0 :(得分:1)
const books = {
"book_1": ["image-1", "image-2", "image-3"], // 3
"book_2": ["image-1"], // 1
"book_3": ["image-1", "image-2"] // 2
}
console.log(Object.entries(books).reduce((acc, [key, array]) => {
acc.push((acc.slice(-1)[0] || 0) + array.length);
return acc;
}, []))
但是...由于不能保证按键顺序,您可能会得到
const books = {
"book_2": ["image-1"], // 1
"book_1": ["image-1", "image-2", "image-3"], // 3
"book_3": ["image-1", "image-2"] // 2
}
console.log(Object.entries(books).reduce((acc, [key, array]) => {
acc.push((acc.slice(-1)[0] || 0) + array.length);
return acc;
}, []))
您想要我正在猜测的特定顺序-因此,对键进行排序
const books = {
"book_2": ["image-1"], // 1
"book_1": ["image-1", "image-2", "image-3"], // 3
"book_3": ["image-1", "image-2"] // 2
}
console.log(Object.entries(books).sort(([a], [b]) => a.localeCompare(b)).reduce((acc, [key, array]) => {
acc.push((acc.slice(-1)[0] || 0) + array.length);
return acc;
}, []))
答案 1 :(得分:-1)
虽然 还是可以遍历对象。
const books = {
"book_1": ["image-1", "image-2", "image-3"], // 3
"book_2": ["image-1"], // 1
"book_3": ["image-1", "image-2"] // 2
}
let sum = 0;
let arr = [];
for(let i in books){
sum += books[i].length;
arr.push(sum);
}
console.log(arr);//[3,4,6]