Reputation: 91
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.
Upvotes: 0
Views: 226
Reputation: 65
<?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.
Upvotes: 0
Reputation: 9675
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
Upvotes: 1
Reputation: 1339
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
Upvotes: 0
Reputation: 31712
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);
Upvotes: 3
Reputation: 97381
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);
Upvotes: 4