use lodash convert one JSON structure to another

Tags: ,



I have a json JSON structure like this

var data = [
      {
        "S1": "$13",
        "S3B/T1": "$15",
        "S3B-N/SS-GG": "$17",
        "S3B-BN/SF-SS/GF-GG": "$18",
        "WDA/WDB": "$15",
        "WDA-CT/WDB-CT": "$18"
      },
      {
        "S1": "$20",
        "S3B/T1": "$23",
        "S3B-N/SS-GG": "$26",
        "S3B-BN/SF-SS/GF-GG": "$27",
        "WDA/WDB": "$23",
        "WDA-CT/WDB-CT": "$27"
      }
    ];

I want to convert data to an output structure like this. Here’s the target with just the result I want to achieve.

    var data = [
        {
          "S1": "$13",
          "S3B": "$15",
          "T1": "$15"
          "S3B-N": "$17",
          "SS-GG": "$17",
          "S3B-BN": "$18",
          "SF-SS": "$18",
          "GF-GG": "$18",
          "WDA": "$15",
          "WDB": "$15",
          "WDA-CT": "$18",
          "WDB-CT": "$18"
        },
        {
          "S1": "$20",
          "S3B": "$23",
          "T1": "$23",
          "S3B-N": "$26",
          "SS-GG": "$26",
          "S3B-BN": "$27",
          "SF-SS": "$27",
          "GF-GG": "$27",
          "WDA": "$23",
          "WDB": "$23",
          "WDA-CT": "$27",
          "WDB-CT": "$27"
        }
    ]

split the key valeu to new object if the value is the same. Thanks in advance.

Answer

You may achieve the desired transformation with Object.entries, Array.prototype.reduce and spread operator for object literals. No lodash is needed.

data.map(item =>
  Object.entries(item).reduce((acc, [key, val]) => ({
    ...acc,
    ...key.split('/').reduce((_acc, _key) => ({
      ..._acc,
      [_key]: val
    }), {})
  }), {})
);
  • map iterates through the top-level array (data)
  • 1st reduce iterates through the properties of the item-object of data and accumulates new object
  • each key of the item-object is being transformed into an array via splitting by / symbol
  • and that sub-array is being accumulated into another object (via 2nd reduce) that would have sub-keys which would keep a single value corresponded to the original key


Source: stackoverflow