Reputation: 1859
I have a nested object
[
{
"name": "Americas",
"categories": [
"No Product Assigned",
"Accessories",
"AP - Apparel",
"FW - Footwear"
]
},
{
"name": "Europe and Middle east",
"categories": [
"No Product Assigned",
"Accessories",
"AP - Apparel",
"FW - Footwear"
]
}
]
where categories can contain further nestings of name and categories,
so far i ve been able to get the depth and the list of all elements in object using
_depthOfCategory = function(object) {
var levelObj = {
level : 0,
name : []
};
var key;
for (key in object) {
if (object[key].name) {
levelObj.name.push(object[key].name);
} else if (typeof (object[key]) === "string") {
levelObj.name.push(object[key]);
}
if (!object.hasOwnProperty(key)) {
continue;
}
if (typeof object[key] === 'object') {
var child = this._depthOfCategory(object[key]);
var depth = child.level + 1;
levelObj.level = Math.max(depth, levelObj.level);
levelObj.name = child.name.concat(levelObj.name);
}
}
return levelObj;
};
where levelObj.length = total depth; levelObj.name = concatenated list of all elements.
Any Ideas on how the below result can be attained
result[0] = "Europe and Middle east"
result [1] = " No Product Assigned"
which are the longest strings in the respective depths.
Upvotes: 0
Views: 86
Reputation: 2592
Something like this would make the trick, I guess.
function getLongest(list, result, level) {
result = result || {};
level = level || 0;
result[level] = result[level] || '';
list.forEach(function(obj) {
var name = typeof obj === 'string' ? obj : obj.name ? obj.name : null;
if (name && name.length > result[level].length) result[level] = name;
if (obj.categories) getLongest(obj.categories, result, level + 1);
});
return result;
}
You can call it like:
getLongest(object);
Upvotes: 1