0

I have array from database with json_encode, like this :

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

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?

thankyou

2
  • 1
    The desired output that you posted is not a javascript array, its an object Commented Jun 17, 2016 at 1:34
  • @HectorBarbossa , oh thankyou for the explain. Commented Jun 17, 2016 at 1:38

2 Answers 2

1

Handle with javascript:

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

//usage

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

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

Or you can handle it with PHP:

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

Comments

0

If I understood it correctly, you are looking for something like

 var arr = [{"uid":"595e7d","name":"Elephant"},{"uid":"701b03","name":"Bird"},{"uid":"29a8c","name":"Lion"}];
 var out = {};
 arr.forEach(function(obj){
    var tempArr = Object.values(obj);
    out[tempArr[0]] = tempArr[1]; 
 });

 console.log(out);

Please note that the code is not too generic and may require modification based on your actual requirement.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.