Skip to content Skip to sidebar Skip to footer

Javascript/lodash Data Transformation

Expected: map which has algo_id as key and temp as values. like below and so on. { '1': { 'temp': { 'a': 1 } }, '101': { 'tem

Solution 1:

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

consttransform = (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), [])

Solution 2:

No need to use lodash, you can do this in plain JavaScript for this.

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

console.log(convert(original, 'algo_id'));

functionconvert(data, key) {
  let process = function(value, key, result) {
    result[value[key]] = value;
    delete result[value[key]][key]; // Remove the `algo_id` key
  };
  returnObject.keys(data).reduce((result, k, i) => {
    if (Array.isArray(data[k])) {
      data[k].forEach(val =>process(val, key, result));
    } else {
      process(data[k], key, result);
    }
    return result;
  }, {});
}
.as-console-wrapper { top: 0; max-height: 100%!important; }
<!--

{
    "1": {
        "temp": {
            "a": 1
        }
    }
}

-->

Solution 3:

With lodash, after getting the values, flatten the mixed array of arrays and objects, use keyBy to convert back to an object with the algo_id as key, and then map the sub object to omit the algo_id property.

const { flow, partialRight: pr, values, flatten, keyBy, mapValues, omit } = _

const fn = flow(
  values, // convert to a mixed array of objects and arrays
  flatten, // flatten to an array of objectspr(keyBy, 'algo_id'), // convert to object with algo_id as keypr(mapValues, pr(omit, 'algo_id')), // remove algo_id from the sub objects
);

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

const result = fn(original);

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

Post a Comment for "Javascript/lodash Data Transformation"