wankdanker / node-object-mapper

Copy properties from one object to another.
MIT License
276 stars 73 forks source link

Patch for how to tell if you are in the array or primative #97

Open tisdadd opened 3 weeks ago

tisdadd commented 3 weeks ago

Hi! πŸ‘‹

Firstly, thanks for your work on this project! πŸ™‚

Today I used patch-package to patch object-mapper@6.2.0 for the project I'm working on.

Anyway, I needed a way to tell in array objects if I was in the array batch of the key, or some other part.

For instance, this data and mapping using just value had troubles for me, but with the added bits worked for my purposes.

const data = [
      {
        randomObjectRecommendations: [
          {
            someBoolean: 'TRUE',
          },
          {
            someBoolean: '',
          },
          {
            someBoolean: '',
          },
        ],
      },
      {
        randomObjectRecommendations: [
          {
            someBoolean: '',
          },
          {
            someBoolean: '',
          },
          {
            someBoolean: '',
          },
        ],
      },
    ]

const mapping = [{'[].randomObjectRecommendations[].someBoolean': {
   key: '[].randomObjectRecommendations[].someBoolean?',
  transform: (value, src, dest, srckey, destkey, ix) => {
    if(ix !== undefined) {
      return value
    }
    return booleanify(value)
}
}}

The ix is there when it is part of the array, otherwise not. I wish I had kept my base object mapper test, as I didn't realize how easy it was to create a PR with patch-package.

Here is the diff that solved my problem:

diff --git a/node_modules/object-mapper/src/object-mapper.js b/node_modules/object-mapper/src/object-mapper.js
index 0adda3a..e5fa6c0 100644
--- a/node_modules/object-mapper/src/object-mapper.js
+++ b/node_modules/object-mapper/src/object-mapper.js
@@ -305,7 +305,7 @@ function update_arr(dest, key, data, keys, context)
     dest = data.reduce(function(dest,d,i) {
       // If the instruction is to update all array indices ('') or the current index, update the child data element.  Otherwise, don't bother
       if (key.ix == '' || key.ix == i) {
-        return update_arr_ix(dest, i, applyTransform(d,dest,context), keys.slice(), context)
+        return update_arr_ix(dest, i, applyTransform(d,dest,context, i), keys.slice(), context)
       }
     }, dest)

@@ -317,9 +317,9 @@ function update_arr(dest, key, data, keys, context)
     return update_arr_ix(dest, '0', data, keys, context)
 }

-function applyTransform(data, dest, context){
+function applyTransform(data, dest, context, ix){
   if (typeof context.transform == 'function') {
-    return context.transform(data, context.src, dest, context.srckey, context.destkey)
+    return context.transform(data, context.src, dest, context.srckey, context.destkey, ix)
   }else{
     return data;
   }

This issue body was partially generated by patch-package.