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

时间:2017-02-21 05:40:24

标签: javascript php json

我有以下json数组:

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

我想只保留title元素并删除其他元素。我试图用php和javascript解决这个问题。

5 个答案:

答案 0 :(得分:4)

在JavaScript中,使用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);




答案 1 :(得分:3)



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);




或者,如果您想获得一系列标题并保持原始数组的完整性:



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);




答案 2 :(得分:1)

使用以下方法在PHP中解决:

$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

答案 3 :(得分:0)

在PHP中

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

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

var_dump($title); 

如果你没有json文件而不是使用json_encode来创建php中的json

答案 4 :(得分:0)

<?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'));
 ?>

试试这段代码,希望它对您有用。