Home > Net >  How to create a JS recursive function to format a data object, but set a level to transform an objec
How to create a JS recursive function to format a data object, but set a level to transform an objec

Time:01-07

const obj2arr = (data, level) => {
  const dataKeys = "object" === typeof(data) && !Array.isArray(data) && Object.keys(data);
  let results = [];
  if (!!dataKeys) {
    for (let dataKey of dataKeys) {
      let obj = {
        name: dataKey
      }
      obj["values"] = data[dataKey] || null;
      if ("object" === typeof(data[dataKey]) && !Array.isArray(data[dataKey]) &&
        data[dataKey] && "object" === typeof(data[dataKey]) && level > 0) {
        obj["values"] = obj2arr(data[dataKey], level);
        --level
      }
        level
      results = [...results, obj];
    }
  }
  return results
}

let b = {
  a: [1, 2],
  b: 3,
  c: 'c',
  d: {
    d1: 'bla',
    d2: 'ble',
    d3: {
      e: 1,
      f: [1, 2],
      g: 'bli',
      h: {
        h1: 1,
        h2: 2
      }
    }
  }
};
res = obj2arr(b, 1);
console.log(res);

CodePudding user response:

You should not have those level and level-- instructions. Instead pass level - 1 to the recursive call:

        obj["values"] = obj2arr(data[dataKey], level - 1);

This way the condition you already have (level > 0) will make sure that only up to the given level the transformation is made.

I didn't touch anything else in your code:

const obj2arr = (data, level) => {
  const dataKeys = "object" === typeof(data) && !Array.isArray(data) && Object.keys(data);
  let results = [];
  if (!!dataKeys) {
    for (let dataKey of dataKeys) {
      let obj = {
        name: dataKey
      }
      obj["values"] = data[dataKey] || null;
      if ("object" === typeof(data[dataKey]) && !Array.isArray(data[dataKey]) &&
        data[dataKey] && "object" === typeof(data[dataKey]) && level > 0) {
        obj["values"] = obj2arr(data[dataKey], level - 1);
      }
      results = [...results, obj];
    }
  }
  return results
}

let b = {
  a: [1, 2],
  b: 3,
  c: 'c',
  d: {
    d1: 'bla',
    d2: 'ble',
    d3: {
      e: 1,
      f: [1, 2],
      g: 'bli',
      h: {
        h1: 1,
        h2: 2
      }
    }
  }
};
res = obj2arr(b, 1);
console.log(res);

  •  Tags:  
  • Related