0

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?

1 Answer 1

1

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.
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.