mesqueeb / find-and-replace-anything

Replace one val with another or all occurrences in an object recursively. A simple & small integration.

Home Page:https://npmjs.com/find-and-replace-anything

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Pass value's path for checkFn on findAndReplaceIf

soknifedev opened this issue · comments

Currently, checkFn receives two things: target and propKey. Which is useful for low complexity objects.
Implementing a propKey's target path will be useful for more complex objects.

For example

      const result = findAndReplaceIf({
        caption: {
          text: 'Github example',
          thumbnail: 'https://soknife.dev/avatar_thumb.jpg'
        },
        items: [{
          taken_at: 1645437935,
          thumbnails: {
            thumbnail_width: 100,
            thumbnail_height: 126,
            sprites: [ "https://soknife.dev/avatar.jpg" ]    
          },
          images: {
            candidates: [{
              width: 720,
              height: 900,
              url: "https://soknife.dev/avatar_f8huefh8dfusih.jpg",
            }, {
              width: 200,
              height: 300,
              url: "https://soknife.dev/avatar_12313213.jpg",
            }, {
              width: 50,
              height: 50,
              url: "https://soknife.dev/avatar_asdsadsaas.jpg",
            }]
          }
        }]
      }, downloadIfSmallest, { checkArrayValues: true });

What if I need to download the smallest image only?

I won't know where "val" came from when downloadIfSmallest is called because it only knows two things: val, propKey, so, implementing a "propPath" may be useful for such task.

this propPath should look like .images.candidates.1.url which is the 50x50 image.

with that path, I should be able to look into .images.candidates.1 of the main object to know if it is the value I am looking for or not (using width and height properties.)

What do you think?

I did it by myself if anyone is interested:

function _findAndReplaceIf(target, checkFn, propKey, propPath, config = { onlyPlainObjects: true, checkArrayValues: false }) {
    const _target = checkFn(target, propKey, propPath);
    if (config.checkArrayValues && isWhat.isArray(_target) && !isWhat.isAnyObject(_target)) {
        return _target.map((value, index) => {
            const ppath = [propPath, index].join('.');
            return _findAndReplaceIf(value, checkFn, undefined, ppath, config);
        });
    }
    if (!isWhat.isPlainObject(_target)) {
        return _target;
    }
    return Object.entries(_target).reduce((carry, [key, val]) => {
        const ppath = [propPath, key].join('.');
        carry[key] = _findAndReplaceIf(val, checkFn, key, ppath, config);
        return carry;
    }, {});
}