Skip to content

Conversation

DarkGhostHunter
Copy link
Contributor

What?

Introduces a method to both base Collection and Arr helpers to transform each array key using a callback.

The Arr::mapKeys() will return a new array with the new keys.

use Illuminate\Support\Arr;

$array = [
    'first_name' => 'John',
    'is_admin' => false
];

$new = Arr::mapKeys($array, fn ($key) => Str::replace('_', '-'));

// [
//     'first-name' => 'John',
//     'is-admin' => false,
// ]

The Collection::mapKeys() will also do the same.

use Illuminate\Support\Collection;use Illuminate\Support\Str;

$collection = Collection::make([
    'first_name' => 'John',
    'is_admin' => false
]);

$collection->mapKeys(fn ($key) => Str::replace('_', '-'));

// \Illuminate\Support\Collection([
//     'first-name' => 'John',
//     'is-admin' => false,
// ])

The main idea for this is to avoid extensive callbacks or using mapWithKeys() just to change the keys. Personally I like to use this to allow the developer to issue either an array of items or multiple parameters, like when these come from parsed JSON into an array without sort guaranties, but also allow to translate each key for frontend reasons.

use Illuminate\Support\Arr;
use Illuminate\Support\Str;

public function make(array|string $name, string $streetAddress = '', string $cityName = '')
{
    if (is_array($name)) {
        return $this->make(...Arr::mapKeys($name, Str::camel(...)))
    }
    
    // ...
}

With that, this PR also introduces mapKeysToCamel and mapKeysToSnake into the Arr helper to conveniently change the case of the array keys, which should be useful when using JSON values as parameters like the above example, or exposing an object as JSON when being serialized to an array.

use Illuminate\Support\Arr;

public function make(array|string $name, string $streetAddress = '', string $cityName = '')
{
    if (is_array($name)) {
        return $this->make(...Arr::mapKeysToCamel($name))
    }
    
    // ...
}

public function toArray(): array
{
    return Arr::mapKeysToSnake(get_object_vars($this));
}

@shaedrich
Copy link
Contributor

With that, this PR also introduces mapKeysToCamel and mapKeysToSnake into the Arr helper to conveniently change the case of the array keys, which should be useful when using JSON values as parameters like the above example, or exposing an object as JSON when being serialized to an array.

What about mapKeysToLower, mapKeysToUpper, mapKeysToKebab, mapKeysToConstantCase, and mapKeysToPascal?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants