xialvjun
xialvjun

Reputation: 1248

how to use _.cloneWith to transform an object?

I want to transform an object like {a: 123, b: '234'} to {a: '123', b: '234'}, so I try code:

var m = {a:123,b:'234'};
var n = _.cloneWith(m, v => {
  if (typeof v === number) return v + '';
});

But I got n just to be a string [object Object]. _.cloneWith send the whole m to the customizer.

But I can not use _.cloneDeepWith beacuse I have different transform logic on different level. Say I want to transform x to y:

var x = {
  a: 123,
  b: '234',
  c: { c0: '345', c1: 456 },
}
// transform x to y
var y = {
  a: '123',
  b: '234',
  c: { c0: 345, c1: 456 },
}

Upvotes: 1

Views: 974

Answers (1)

Ori Drori
Ori Drori

Reputation: 191986

The _. cloneDeepWith() customizer is called with the (value [, index|key, object, stack]), so you can use the key to supply a different clone function.

In this case, I call _.cloneDeepWith(), but with a different logic:

const cloneC = obj => _.cloneDeepWith(obj, v => 
  _.isString(v) && _.isNumber(+v) ? Number(v) : undefined
);

const clone = obj => _.cloneDeepWith(obj, (v, k) => {
  if(_.isNumber(v)) return String(v);
  
  if(k === 'c') return cloneC(v);
});

const m = {"a":123,"b":"234"};
const x = {"a":123,"b":"234","c":{"c0":"345","c1":456}};

console.log(clone(m));
console.log(clone(x));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous"></script>

Upvotes: 1

Related Questions