array/push.js

  1. import toArray from 'lodash/toArray'
  2. import update from '../object/update'
  3. /**
  4. * Replaces by a new array containing the elements of the former array and one or more elements added to the end.
  5. * @function push
  6. * @memberof array
  7. * @param {Object} object The object to modify.
  8. * @param {Array|string} path The path of the property to set.
  9. * @param {...*} values The values to add.
  10. * @return {Object} Returns the updated object.
  11. * @example <caption>Add one element.</caption>
  12. * push({ nested: { prop: [1, 2] } }, 'nested.prop', 3) // => { nested: { prop: [1, 2, 3] } }
  13. * @example <caption>Add several elements.</caption>
  14. * push({ nested: { prop: [1, 2] } }, 'nested.prop', 3, 4) // => { nested: { prop: [1, 2, 3, 4] } }
  15. * @see {@link https://lodash.com/docs#toArray|lodash.toArray} for more information.
  16. * @see {@link https://mdn.io/Array.prototype.push|Array.prototype.push} for more information.
  17. * @see {@link object.update|update} for more information.
  18. * @since 0.1.7
  19. */
  20. export default update((value, ...values) => {
  21. const newValue = toArray(value)
  22. newValue.push(...values)
  23. return newValue
  24. })