简体   繁体   中英

Change the format of JavaScript array when source is PHP

I am currently working on laravel and my project requires me to use autocomplete for dropdowns.

However, the object returned from the following

$companies = Companies::all()->pluck('company_name','id')->toArray();

and converted to js array using the following

var companies = <?php echo json_encode($companies) ?>;

returns the following format of array

{ 2: "Jadon Technology", 
    58: "Samsung",
    59: "Sony",
    60: "Sujan",
    61: "Superman", 
    68: "Vivo", 
    84: "Iphone", 
    85: "Oppo", 
  }

I want the array as given below.

var companies = [
    { id: 2, value: "Jadon Technology"} , 
    { id: 58, value: "Samsung"} ,
    { id: 59, value: "Sony"} ,
    { id: 60, value: "Sujan"} ,
    { id: 61, value: "Superman"} , 
    { id: 68, value: "Vivo"} , 
    { id: 84, value: "Iphone"} , 
    { id: 85, value: "Oppo"} , 
  ];

Am i doing something wrong or is there any other way to convert into said format? Please someone help me. Suggestions including php/laravel/javascript oriented are welcomed. PS: no foreach loop because i have to implement the same in numerous places in the same project.

The pluck function formats the data that way, the first parameter is the value key and the second is the key value. If you want key value pairs, you should use select .

$companies = Companies::select('company_name', 'id')->get()->toArray();

Why not implement a function to do the work, then call the function before json_encode:

   function convert($arr) { 
       $tmp = array();
       foreach ($arr as $k => $v) {
          $tmp[] = array("id" => $k, "value" => $v)
       }
       return $tmp;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM