如何在json数组中保留特定元素并删除其他元素?

I have following json array:

[
 { "id": "1", "title": "Pharmacy", "desc": "xyz"},
 { "id": "21", "title": "Engineering", "desc": "xyz"},
 { "id": "30", "title": "Agriculture", "desc": "xyz"},
 ...
]

I want to keep only title element and remove other. I tried to solve this using php and javascript.

var arr = [
 { "id": "1", "title": "Pharmacy", "desc": "xyz"},
 { "id": "21", "title": "Engineering", "desc": "xyz"},
 { "id": "30", "title": "Agriculture", "desc": "xyz"}
];

arr.forEach(function(obj) {
  delete obj.id;
  delete obj.desc;
});

console.log(arr);

Or if you want to get an array of titles and keep the original array intact:

var arr = [
 { "id": "1", "title": "Pharmacy", "desc": "xyz"},
 { "id": "21", "title": "Engineering", "desc": "xyz"},
 { "id": "30", "title": "Agriculture", "desc": "xyz"}
];

var titles = arr.map(function(obj) {
  return obj.title;
});

console.log(titles);

</div>

In JavaScript, using Array.prototype.map():

let array = [
 { "id": "1", "title": "Pharmacy", "desc": "xyz"},
 { "id": "21", "title": "Engineering", "desc": "xyz"},
 { "id": "30", "title": "Agriculture", "desc": "xyz"}
];
let mapped = array.map(i => ({title: i.title}));

console.log(mapped);

</div>

In PHP

$string = file_get_contents('yourjsonfile.json');
$json = json_decode($string,true); 

$title = [] ;
foreach($json as $t){
    $title[] =  $t['title'] ;
} 

var_dump($title); 

if you don't have json file than you have use json_encode for creating json in php

Solve it in PHP using:

$title = array();
foreach($arr as $val) {
  $json = json_decode($val, TRUE);
  $title[]['title'] = $json['title'];
}

$titleJson = json_encode($title);

var_dump($titleJson); //array of titles
<?php
function setArrayOnField($array,$fieldName){
  $returnArray = [];
  foreach ($array as $val) {
    $returnArray[] = [$fieldName=>$val[$fieldName]];
  }
  return $returnArray;
}
$list = [
  [ "id"=> "1", "title"=> "Pharmacy", "desc"=> "xyz"],
  [ "id"=> "2", "title"=> "Computer", "desc"=> "abc"],
  [ "id"=> "3", "title"=> "Other", "desc"=> "efg"]
];
print_r(setArrayOnField($list,'title'));
 ?>

Try this code hope it's worth for you.