Search code examples
javascriptlodash

JavaScript/lodash data transformation


var original = {
  "8": [{
      "temp": {
        "a": 1
      },
      "algo_id": 1
    },
    {
      "temp": {
        "a": 2
      },
      "algo_id": 101
    }
  ],
  "13": {
    "temp": {
      "temp1": [1, 2]
    },
    "algo_id": 2
  }
};

const values = _.values(original);
const temp = _.map(values, (v) => {
  if (_.isArray(v)) {
    return _.mapValues(_.keyBy(v, 'algo_id'), a => _.pick(a, 'temp'));
  }
});

console.log(temp);
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Expected:

map which has algo_id as key and temp as values. like below and so on.

      {
    "1": {
        "temp": {
            "a": 1
        }
    },
    "101": {
        "temp": {
            "a": 2
        }
    },
    "2": {
        "temp": {
            "temp1": [1, 2]
        }
    }
}

How to add key and values which are not array in the object.?


Solution

  • One way to do this (not using lodash) is the following:

    const transform = (original) => Object.values(original)
      .flat()
      .reduce((all, {algo_id, ...rest}) => ({...all, [algo_id]: rest}), {})
    
    const original ={"13": {"algo_id": 2, "temp": {"temp1": [1, 2]}}, "8": [{"algo_id": 1, "temp": {"a": 1}}, {"algo_id": 101, "temp": {"a": 2}}]}
    
    console.log(transform(original))

    But this makes the assumption that you can use the sibling of algo_id as is. Your example seems to show further processing of it that I can't see any rule for.

    If your target environments don't support flat, you can replace this:

          .flat()
    

    with this:

          .reduce((a, b) => a.concat(b), [])