Skip to content Skip to sidebar Skip to footer

Converting Formatted Json Object To Array Of Objects On The Same Level (flatten) And Sum Up On Each Level

Have the following tree json object: { 'Season1': { 'Title1': { 'a1': { 'val1': '100', 'val2': '200', 'val3': '300' }, 'a2': {

Solution 1:

Try if this works! Might be a little tricky to explain the code.

I have added a couple of comments at relevant parts of code.

var data = {
  Season1: {
    Title1: {
      a1: {
        val1: "100",
        val2: "150",
        val3: "100"
      },
      a2: {
        val1: "100",
        val2: "200",
        val3: "300"
      }
    },
    Title2: {
      c1: {
        val1: "100",
        val2: "200",
        val3: "300"
      },
      d2: {
        val1: "100",
        val2: "200",
        val3: "300"
      }
    }
  },
  Season2: {
    Title1: {
      a1: {
        val1: "100",
        val2: "200",
        val3: "300"
      },
      a2: {
        val1: "100",
        val2: "200",
        val3: "300"
      }
    },
    Title2: {
      c1: {
        val1: "100",
        val2: "200",
        val3: "300"
      },
      d2: {
        val1: "100",
        val2: "200",
        val3: "300"
      }
    }
  }
};

function Format(obj, depth = 0) {
  return Object.entries(obj).flatMap(([key, val]) => {
    if (
      Object.keys(val).some(function(k) {
        return typeof val[k] === "object";
      })
    ) {
      // Pad keys with spaces based on depth
      let o = {
        name: key.padStart(depth * 4 + key.length)
      };
      const children = Format(val, depth + 1);
      // Get the sum of children that are only only one level deep 
      const childrenSum = children
        .filter(
          ({
            name
          }) =>
          name.length - name.replace(/\s/g, "").length === (depth + 1) * 4
        )
        // Filter out the name key as they are not numbers 
        .reduce((acc, temp) => {
          Object.entries(temp)
            .filter(([key, val]) => key !== "name")
            .forEach(([key, val]) => {
              acc[key] = (acc[key] || 0) + Number(val);
            });
          return acc;
        }, {});
      o = { ...o,
        ...childrenSum
      };
      return [o, ...children];
    } else {
      let o = {
        name: key.padStart(depth * 4 + key.length)
      };
      Object.keys(val).map(function(a) {
        o[a] = val[a];
      });
      return [o];
    }
  });
}

console.log(Format(data));

Post a Comment for "Converting Formatted Json Object To Array Of Objects On The Same Level (flatten) And Sum Up On Each Level"