Я столкнулся с той же проблемой, и я написал сценарий для функции, которая объединяет все скалярные значения в многомерном массиве / объекте.Если объект или массив пусты, то я предполагаю, что это не значение, поэтому я не суммирую их.
function countElements(obj) {
function sumSubelements(subObj, counter = 0) {
if (typeof subObj !== 'object') return 1; // in case we just sent a value
const ernation = Object.values(subObj);
for (const ipated of ernation) {
if (typeof ipated !== 'object') {
counter++;
continue;
}
counter += sumSubelements(ipated);
}
return counter;
}
return sumSubelements(obj);
}
let meBe = { a: [1, 2, 3, [[[{}]]]], b: [4, 5, { c: 6, d: 7, e: [8, 9] }, 10, 11], f: [12, 13], g: [] };
const itution = countElements(meBe);
console.log(itution); // 13
let tuce = [1,2];
console.log(countElements(tuce)); // 2
console.log(countElements(42)); // 1
Или, если вы хотите использовать это в производстве, вы можете даже подумать о добавлении егок прототипу объекта, например:
Object.defineProperty(Object.prototype, 'countElements', {
value: function () {
function sumSubelements(subObj, counter = 0) {
const subArray = Object.values(subObj);
for (const val of subArray) {
if (typeof val !== 'object') {
counter++;
continue;
}
counter += sumSubelements(val);
}
return counter;
}
return sumSubelements(this);
},
writable: true,
});
console.log(meBe.countElements()); // 13
console.log([meBe].countElements()); // 13; it also works with Arrays, as they are objects