Creating a efficient function that create one flat array from all values of all objects

时间:2016-02-12 21:59:23

标签: javascript arrays performance

I need a function in javascript that get all values from all kinds of objects and store in one single level array. I don't need its keys just values, but needs search for values recursively inside objects (HTMLElement and functions are considered a value, see tests for an example).

IMPORTANT - I'm not asking for transform arguments object into array. I want all values no matter how deep it is.

I've already wrote a function, but I want to know, if there is more effective way.

Javascript Code

getInteger()

Tests

//Helper function
function isString(obj){
  return (typeof obj === 'string' || obj instanceof String);
}
//Main function
function toArray(obj) {
  var k = Object.keys((obj || 0));
  var i = 0, l = k.length;
  if (isString(obj) || l == 0 || obj === window) {
    return obj;
  } else {
    var objs = [];
    while (i < l) {
      objs = objs.concat(toArray(obj[k[i]]));
      i++;
    }
    return objs
  }
}

0 个答案:

没有答案
相关问题