优化功能以在对象中查找嵌套属性?

时间:2019-02-21 06:04:25

标签: javascript typescript optimization

我做了以下函数,该函数递归地遍历一个对象,并尝试查找该对象中是否存在属性。如果是这样,它将返回该属性,如果找不到该属性,则返回null:

export const findNestedPropertyInObject = (sourceObject: any, targetKey: string) => {
  let results: any;
  const maxIterations = 100;
  let currentIteration = 0;
  const searchInObject = (obj: any, targetKey: string) => {
    const keys = obj.length ? [] : Object.keys(obj);
    if (keys && keys.length) {
      if (keys.includes(targetKey)) {
        results = obj[targetKey];
        return;
      } else {
        keys.forEach((key: string) => {
          if (currentIteration >= maxIterations) {
            return;
          }
          currentIteration++;
          searchInObject(obj[key], targetKey);
        });
      }
    }
  };

  searchInObject(sourceObject, targetKey);
  return results;
};

这是示例对象:

const aggregations = {
  most_used_skills: {
    doc_count: 388,
    skill: {
      doc_count_error_upper_bound: 10,
      sum_other_doc_count: 325,
      buckets: [
        {
          key: 'C++ Programming Language',
          doc_count: 15,
        },
        {
          key: 'Javascript',
          doc_count: 14,
        },
        {
          key: 'ExtJS',
          doc_count: 12,
        },
        {
          key: 'Amazon Web Services',
          doc_count: 11,
        },
        {
          key: 'Android',
          doc_count: 11,
        },
      ],
    },
  },
};

这是我调用它的方式:

console.log(findNestedPropertyInObject(aggregations, 'buckets'));

我的问题是,如何优化此方法?我可以对此添加哪些安全检查,以使其更具容错性和鲁棒性?

1 个答案:

答案 0 :(得分:0)

export const findNestedPropertyInObject = (sourceObject: any, targetKey: string) => {
let results: any;
const maxIterations = 100;
let currentIteration = 0;
const searchInObject = (obj: any, targetKey: string) => {

    const keys = (obj.length)? obj : Object.keys(obj); // if obj is object get keys as an array
    if ( currentIteration < maxIterations && typeof keys === 'object') // checking if it actually an Array (js treat array as object type)
    {   
        if (keys.includes(targetKey))
        {
            results = obj[targetKey];
            currentIteration = maxIterations; // to stop recursive calling
            return; //optional
        } 
        else
        {
            keys.forEach((key: any) => {
            currentIteration++;
            const innerkeys = (obj[key])? obj[key] : key; // to check if 'key' is key of object or object itself
            searchInObject(innerkeys, targetKey);
            });
        }
    }
};

searchInObject(sourceObject, targetKey); 
return results
};