嵌套对象中最长的字符串

时间:2015-08-31 09:01:51

标签: javascript

我有一个嵌套对象

[
    {
        "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"
        ]
    }
]

其中类别可以包含名称和类别的进一步嵌套,

到目前为止,我已经能够使用

获取对象中所有元素的深度和列表
_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;
        };

其中levelObj.length =总深度; levelObj.name =所有元素的连接列表。

关于如何实现以下结果的任何想法

result[0] = "Europe and Middle east"
result [1] = " No Product Assigned"

是相应深度中最长的字符串。

1 个答案:

答案 0 :(得分:1)

我猜这样的事情会成为伎俩。

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;
}

你可以这样称呼:

getLongest(object);