Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten an nested array of objects using Lodash

Tags:

My object looks like this:

const features = [{
                  'name': 'feature1', 'tags':
                  [{'weight':10, 'tagName': 't1'},{'weight':20, 'tagName': 't2'}, {'weight':30, 'tagName': 't3'}]
                  },
                  {
                  'name': 'feature2', 'tags':
                  [{'weight':40, 'tagName': 't1'}, {'weight':5, 'tagName':'t2'}, {'weight':70, 'tagName':'t3'}]
                  },
                  {
                  'name': 'feature3', 'tags':[
                  {'weight':50, 'tagName': 't1'}, {'weight':2, 'tagName': 't2'}, {'weight':80, 'tagName': 't3'}]
                 }]

I would like my output to look something like this:

const features = [{'name':'feature1', 'weight':10, 'tagName':'t1'}, 
                  {'name':'feature1', 'weight':20, 'tagName':'t2'}, ...
                  {'name':'feature3', 'weight':80, 'tagName':'t3'}]

I tried to merge and the flatten but it does not work.

Update 1 I tried this:

let feat = features;

results = []

_.each(feat, (item) => { 
                        console.log(item);
                        results.push(_.flatten(_.pick(item.tags, 'weight'))); // pick for certain keys. 
                       }

Update 2 This solved my problem

_.each(features, (item) => { 
  _.each(item.tags, (itemTag) => { 
    results.push({'name':item.name, 'weight':itemTag.weight, 'tagName':itemTag.tagName})})})

But I want to know if there is a more lodash way to do this!

like image 818
suprita shankar Avatar asked Feb 20 '17 22:02

suprita shankar


People also ask

How do you flatten a nested array of objects?

The “Array. flat()” method is embedded in ES6 that enables you to “flatten” a nested JavaScript Array. This method returns a new array in which all of the elements of sub-arrays are concatenated according to the specified depth.

How do you flatten an array using Lodash?

The Lodash. flatten() method is used to flatten the array to one level deep. Parameter: This method accepts single parameter array that holds simple array or array of arrays. Return Value: The return type of this function is array.

How do you flatten an object in an array?

You use the flat() method for concatenating sub-arrays recursively into a single array. The flat() method takes a depth value as its parameter which is optional depending on the depth of the array you wish to flatten (concatenate). The flat() method takes in 1 as a depth by default.

Can you flatten an array?

Flattening an array is a process of reducing the dimensionality of an array. In other words, it a process of reducing the number of dimensions of an array to a lower number.


1 Answers

The approach below uses flatMap to flatten tags acquired through map. Finally, use the spread operator to assign the values from tag and the feature's name.

const result = _.flatMap(features, ({ name, tags }) =>
  _.map(tags, tag => ({ name, ...tag }))
);

const features = [{
    'name': 'feature1',
    'tags': [{
      'weight': 10,
      'tagName': 't1'
    }, {
      'weight': 20,
      'tagName': 't2'
    }, {
      'weight': 30,
      'tagName': 't3'
    }]
  },
  {
    'name': 'feature2',
    'tags': [{
      'weight': 40,
      'tagName': 't1'
    }, {
      'weight': 5,
      'tagName': 't2'
    }, {
      'weight': 70,
      'tagName': 't3'
    }]
  },
  {
    'name': 'feature3',
    'tags': [{
      'weight': 50,
      'tagName': 't1'
    }, {
      'weight': 2,
      'tagName': 't2'
    }, {
      'weight': 80,
      'tagName': 't3'
    }]
  }
];

const result = _.flatMap(features, ({ name, tags }) =>
  _.map(tags, tag => ({ name, ...tag }))
);

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

Here's a plain javascript solution that uses Array#reduce and Array#map with the help of Array#concat to flatten the array.

const result = features.reduce(
  (result, { name, tags }) => result
    .concat(tags.map(tag => ({ name, ...tag }))), 
  []
);

const features = [{
    'name': 'feature1',
    'tags': [{
      'weight': 10,
      'tagName': 't1'
    }, {
      'weight': 20,
      'tagName': 't2'
    }, {
      'weight': 30,
      'tagName': 't3'
    }]
  },
  {
    'name': 'feature2',
    'tags': [{
      'weight': 40,
      'tagName': 't1'
    }, {
      'weight': 5,
      'tagName': 't2'
    }, {
      'weight': 70,
      'tagName': 't3'
    }]
  },
  {
    'name': 'feature3',
    'tags': [{
      'weight': 50,
      'tagName': 't1'
    }, {
      'weight': 2,
      'tagName': 't2'
    }, {
      'weight': 80,
      'tagName': 't3'
    }]
  }
];

const result = features.reduce(
  (result, { name, tags }) => result
    .concat(tags.map(tag => ({ name, ...tag }))), 
  []
);

console.log(result);
.as-console-wrapper{min-height:100%;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
like image 195
ryeballar Avatar answered Sep 18 '22 15:09

ryeballar