简体   繁体   中英

Loop over Object and return the length of each key cumulatively in an array

I have an object that I would like to loop over and return the cumulative length of each key in an array. Below is the object and the ideal output:

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]

I know it's not possible to loop over an object, but I've used Object.key() and then .reduce() to get the length of each key, I just can't work out how to piece them together. Any help would be greatly appreciated

 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; }, [])) 

 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; }, [])) 

However ... since key order is not guaranteed, you may end up with

 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; }, [])) 

and you want a particular order I'm guessing - so, sort the keys

 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; }, [])) 

It is possible to loop over an object though.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM