Mohammad Hosseini
Mohammad Hosseini

Reputation: 1797

How to convert array with objects to one object like Laravel Request object

I have an array like this:

[{FirstName: "fff"},
{LastName: null},
{Nationality: null},
{Year: null},
{Month: null},
{Day: null}]

I need to convert it to one object like this: (with Laravel or with JS)

{FirstName: "fff",
LastName: null,
Nationality: null,
Year: null,
Month: null,
Day: null}

I need one object exactly like Laravel request object. How can I do this?

Upvotes: 0

Views: 485

Answers (1)

TsaiKoga
TsaiKoga

Reputation: 13394

Assuming the array nest with objects is variable $a

function multipleObjsToObj($a) {
    $b = json_encode($a, true);     // encode to string
    $array = json_decode($b, true); // decode to all array

    // use collection flatMap or mapWithKeys to flatten with keys:
    // $flatten_array = collect($array)->mapWithKeys(function($item){return $item;})->toArray();
    $flatten_array = collect($array)->flatMap(function($item){return $item;})->all();

    return (object) $flatten_array; // here become to object.
}

Upvotes: 1

Related Questions