0

Using a lodash, I want to transform an object that contains array into array of objects. here is an example:

Original object :

[
  {
    name:"name1"
    params: [{param: "value1"}, {param: "value2"}]
  },
  {
    name:"name2"
    params: [{param: "value3"}, {param: "value4"}]
  }
]

After transformation:

[
  {name:"name1", param: "value1"},
  {name:"name1", param: "value2"},
  {name:"name2", param: "value3"},
  {name:"name2", param: "value4"}
]

Whats the easiest way to achieve this ? Thanks

[EDIT]

Till now I implemented the function below, but I'm almost sure there must be more elegant solution for my problem.

transform (res) {

            const data = [];

            _.each(res, (obj) => {
                const params = _.pick(obj, ['params']);
                const withoutParams = _.omit(obj, 'params');
                _.each(params.params, (param) => {
                    data.push(_.assign(param, withoutParams));
                });
            });
            console.log('data', data);

            return data

        }

1 Answer 1

1

You can _.map() the params and the name of each object into an array of objects, and then _.flatMap() all objects arrays into one array:

var arr = [
  {
    name:"name1",
    params: [{param: "value1"}, {param: "value2"}]
  },
  {
    name:"name2",
    params: [{param: "value3"}, {param: "value4"}]
  }
];

var newArr = _.flatMap(arr, function(obj) {
  return _.map(obj.params, function(param) {
    return {
      name: obj.name,
      param: param.param
    };
  });
});

console.log(newArr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

And this is the ES6 version using Array.prototype.map(), arrow functions, and destructuring:

const arr = [
  {
    name:"name1",
    params: [{param: "value1"}, {param: "value2"}]
  },
  {
    name:"name2",
    params: [{param: "value3"}, {param: "value4"}]
  }
];

const newArr = _.flatMap(arr, ({
  name, params
}) => params.map(({
  param
}) => ({
  name, param
})));

console.log(newArr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.