Skip to content Skip to sidebar Skip to footer

Flatten Hierarchical Data

I have a data structure like this: { name: 'test', config: { ... }, prev: { name: 'test1.1', config: { ... }, prev: { name: 'test1.1

Solution 1:

It's easier to use plain js, like this

const data = {
    name: 'test',
    config: { },
    prev: { name: 'test1.1',
        config: { },
        prev: {
            name: 'test1.1.1',
            config: {  },
            prev: { name: 'test1.1.1.1', config: { }, prev: undefined }
        }
    }
};

functionflatten (data) {
  let result = [];
  
  while (data) {
    result.push({ name: data.name, config: data.config });
    data = data.prev;
  }
  
  return result;
}

console.log(flatten(data));

// get only namesconst res = flatten(data).map(el => el.name);
console.log(res);

Solution 2:

Recursive strategy

var data = {
    name: 'test',
    config: { },
    prev: {
        name: 'test1.1',
        config: { },
        prev: {
            name: 'test1.1.1',
            config: {  },
            prev: {
                name: 'test1.1.1.1',
                config: { },
                prev: undefined
            }
        }
    }
};

var reduced = flatten(data, function(item) {
    return { name: item.name, config: item.config };
});

print(reduced.map(function(item) { return item.name }).join(', '));
 
functionflatten(data, reducerFn, result) {
    result = result || [];
    if (data === undefined) return result;
    returnflatten(data.prev, reducerFn, result.concat([reducerFn(data)]));
}

/* For Display Purposes Only */functionprint(str) {
    document.getElementById('display').innerHTML += str + '<br />';
}
<divid="display"></div>

Post a Comment for "Flatten Hierarchical Data"