我有一个对象,我想遍历它,并返回数组中每个键的累积长度。下面是对象和理想输出:
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;
}, []))
发布于 2019-09-02 13:02:51
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;
}, []))
发布于 2019-09-02 13:04:58
不过,可以在对象上循环。
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]https://stackoverflow.com/questions/57757322
复制相似问题