如何将带有对象的数组转换为一个对象,如Laravel Request对象



我有一个这样的数组:

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

我需要将它转换为一个这样的对象:(使用Laravel或JS(

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

我需要一个与Laravel请求对象完全相同的对象。我该怎么做?

假设带有对象的数组嵌套为变量$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.
}

最新更新