febri it febri it - 6 months ago 12
Javascript Question

Convert array from php to javascript

I have array from database with json_encode, like this :


but how to make the array just display the record not with the field/column name, when i show in javascript like this :

javascript array :

"595e7d": "Elephant",
"701b03": "Bird",
"29a8c": "Lion"

whether it should be done in php or javascript?



Handle with javascript:

function transfrom (arrs){
  return arrs.reduce((init, arr) => {
      init[arr.uid] = arr.name
      return init
 , {})


let arrs = [{"uid":"595e7d","name":"Elephant"},{"uid":"701b03","name":"Bird"},{"uid":"29a8c","name":"Lion"}]

// {595e7d: "Elephant", 701b03: "Bird", 29a8c: "Lion"}

Or you can handle it with PHP:

$arr = array (
  array('uid' =>"595e7d", "name"=>"Elephant"), 
  array("uid" =>"701b03", "name" =>"Bird"), 
  array("uid" =>"29a8c", "name" =>"Lion")

function transform($v1, $v2) {
    $v1[$v2["uid"]] = $v2["name"];
    return $v1;    

echo json_encode(array_reduce($arr, "transform", array())); 
// { 
//     "595e7d": "Elephant",
//     "701b03": "Bird",
//     "29a8c": "Lion" 
// }