Why lodash converts my array into object?

僤鯓⒐⒋嵵緔 提交于 2019-12-06 08:35:34

main two problems one which was mention by @Akrion for that you can do something as below:

removeFalsies (obj) {

return _.transform(obj, function (o, v, k, l) {

    // here you have to check for array also as typeof will return object for array also
  if (v && _.isObject(v) && !_.isArray(v)) {

    if (v !== '' && !_.omitBy(v, _.isObject)) {
      o[k] = removeFalsies(v);
    }

  } else if(_.isArray(v)) {
  if(!o.hasOwnProperty(k)) o[k] = [];

  //And if it is array loop through it

  _.forEach(v, function(v1, k1) {
     o[k].push(removeFalsies(v1));
  });

  } else if (v === false) {
    o[k] = v;
  } else if (v) {
    o[k] = v;
  }
});
}

while calling function just try to remove mapValues as it create object and convert array in objects because of that your key 0 is getting converted to key

removeEmptyObjects =function (obj) {
      return _(obj).pickBy(_.isObject).omitBy(_.isEmpty).assign(_.omitBy(obj, _.isObject)).value();
}

Hope this will help you, not tested properly yes just short description.

You issue is in your function removeFalsies where you do not account properly for arrays. Remember Arrays are also objects and your check for if (v && typeof v === 'object') is not sufficient.

What happens is that you do:

if (v && typeof v === 'object') {
  if (v !== '') {
    o[k] = _.removeFalsies(v);
  }
}

Where when you pass an array in that _.transform the k is 0 and you end up creating an object with key 0 which value is then _.removeFalsies(v);

Just put a breakpoint or debugger in that if and you can easily see the issue.

Also note that lodash already has plenty of methods to check for objects like _.isObject as well as arrays _.isArray ... _.isString & _.isEmpty etc.

If your code uses

typeof v === 'object'

it will return true for arrays.

To check for array, use

Array.isArray(t)

Treating array as object and iterating over keys will result in your issue.

Sample Function To Recurse But Not Process Arrays

function removeFalsies(obj) {
  return _.transform(obj, function(o, v, k, l) {
      if (Array.isArray(obj) {
          for (let arrItem of obj) {
            removeFalsies(arrItem);
          }
          return
        }
        // else not array...
      })
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!