循环对象并在数组中累积返回每个键的长度

呼叫替代

我有一个对象,我想循环并返回数组中每个键的累积长度。下面是对象和理想的输出:

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

雅罗曼达 X

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档