Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive loop using lodash

I am trying to manipulate n-level deep array/object using lodash. Recursive map function or using a loop is not a perfect solution.

I have sample object like this, on key, it could be array or object. I want to manipulate key value in a single go to false using loop it tedious way. Do I can manipulate using lodash to completely change the value to boolean or something else.

var a = {key1:true, key2:true, key3:[{key1:true, key5:true}], key6:true};
like image 786
Sankalp Avatar asked Mar 08 '17 23:03

Sankalp


1 Answers

You can use cloneDeepWith to achieve the same result.

var result = _.cloneDeepWith(a, function(v) {
  if(!_.isObject(v)) {
    return false;
  }
});

var a = {
  key1: true,
  key2: true,
  key3: [{
    key1: true,
    key5: true
  }],
  key6: true
};

var result = _.cloneDeepWith(a, function(v) {
  if(!_.isObject(v)) {
    return false;
  }
});

console.log(result);
body > div { min-height: 100%; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
like image 102
ryeballar Avatar answered Nov 11 '22 19:11

ryeballar