laravel-collection-macros icon indicating copy to clipboard operation
laravel-collection-macros copied to clipboard

pluckMany dotted key support

Open sfinktah opened this issue 1 year ago • 4 comments

To bring pluckMany inline with various other pluck implementations, including Collections::pluck (Arr::pluck), this allows the specification of dotted keys.

e.g.,

$ar = collect($chunk)
    ->pluckMany(['id', 'handle', 'variants.edges.0.node.sku', 'spaghetti']);

sfinktah avatar Oct 29 '23 12:10 sfinktah

Dear contributor,

because this pull request seems to be inactive for quite some time now, I've automatically closed it. If you feel this pull request deserves some attention from my human colleagues feel free to reopen it.

spatie-bot avatar Mar 01 '24 11:03 spatie-bot

@spatie-bot Dear unhelpful bot, I cannot control the reactions of your masters.

sfinktah avatar Mar 18 '24 15:03 sfinktah

Could you document this?

freekmurze avatar Mar 18 '24 15:03 freekmurze

Dear human :)

How would you like it documented, it's how lodash (though not underscore) behaves when a string key is specified to _.map

It's also how Collection::pluck operates. If you would permit me a slight rudeness, you should be documenting why your pluckMany doesn't operated on dotted values.

    public static function pluck($array, $value, $key = null)
    {
        $results = [];

        [$value, $key] = static::explodePluckParameters($value, $key);

        foreach ($array as $item) {
            $itemValue = data_get($item, $value);
    function data_get($target, $key, $default = null)
    {
        if (is_null($key)) {
            return $target;
        }

        $key = is_array($key) ? $key : explode('.', $key);

        foreach ($key as $i => $segment) {
            unset($key[$i]);

            if (is_null($segment)) {
                return $target;
            }

            if ($segment === '*') {
                if ($target instanceof Collection) {
                    $target = $target->all();
                } elseif (! is_iterable($target)) {
                    return value($default);
                }

                $result = [];

                foreach ($target as $item) {
                    $result[] = data_get($item, $key);
                }

                return in_array('*', $key) ? Arr::collapse($result) : $result;
            }
// ...

sfinktah avatar Mar 18 '24 15:03 sfinktah

Great macro. When will be merged 👀

lazerg avatar Jul 02 '24 03:07 lazerg

Thanks!

freekmurze avatar Jul 02 '24 13:07 freekmurze