New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature request: _.push #2288
Comments
I use this pattern in Lodash too though I'm not digging the name Internally I have a We'll keep an eye on the popularity of the request. |
Yeah, the name may be debatable, but I think the pattern is worthy. I do like having push in the name as Perhaps |
This leaves us some flexibility to expand to other array operations later, whereas I think having |
👍 |
Here's my first draft of getOrAddKey. Feel free to join me in testing. I'll try and release the lib-demo-util 0.1.8 asap, until then you'll have to stub it somehow or use own tests. |
_.set(o, 'arr[]', val); Why not make It'd be a breaking change though. In the current version this line assigns |
pushSafe.ts import { get, set, isArray } from 'lodash'
import { PropertyPath } from 'lodash'
/**
* 根据object对象的path路径,
* 安全向数组(不存则会创建该数组)的末尾添加一个或多个元素,并返回新的长度。
* @author https://github.com/CongAn
*/
export function pushSafe<V>(object: object, path: PropertyPath, ...items: V[]): number
export function pushSafe<V, T extends object>(object: T, path: PropertyPath, ...items: V[]): number {
let array = get(object, path)
if (array === undefined) {
set(object, path, array = [])
}
if (!isArray(array)) {
throw new Error('The object path of push is not an array.');
}
return array.push(...items)
}
export default pushSafe |
When transforming data structures and adding to nested arrays (or creating an array on the fly), we frequently see the following pattern:
It would be convenient to replace this with a nice, readable single line. A lodash push method could follow the same signature as _.has, _.get, _.set, and friends:
For example, when looping through a data set...
could be simplified to a single line...
The text was updated successfully, but these errors were encountered: