How to merge javascript object containing symbols?

Viewed 718

I'm trying to merge two objects with lodash merge, but it doesn't work with symbols. Is there any alternative utility?

    import {merge} from 'lodash';
    import {Op} from 'sequelize';

    const selectA = {
        where: {
            text: "something"
        }
    };

    const selectB = {
        where: {
            date_from: {
                [Op.lt]: Sequelize.literal('NOW()')
            }
        }
    };

    console.log(_.merge(selectA, selectB));

Output:

{ where: { text: 'something', date_from: {} } }
2 Answers

You can use _.mergeWith() and supply a merge function that uses spread.

Note: look at the browser's console. The snippet's console doesn't display symbols.

const Op = {
  lt: Symbol('symbol')
}

const selectA = {
  num: 15,
  where: {
    text: "something"
  }
};

const selectB = {
  num: 30,
  where: {
    date_from: {
      [Op.lt]: 'symbol value'
    }
  }
};

const result = _.mergeWith(selectA, selectB, (a, b) => {
  if (!_.isObject(b)) return b;
  
  return Array.isArray(a) ? [...a, ...b] : { ...a, ...b }
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

Related