2017-02-21 138 views
0

我有以下JSON數組:如何保留特定元素並刪除json數組中的其他元素?

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

我想只保留標題元素和刪除等。我試圖解決這個使用PHP和JavaScript。

+0

如果你只保留一個屬性,你可能會轉換爲一個字符串數組:'[「藥房」,「工程」,「農業」,...]'。 – nnnnnn

回答

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

+0

謝謝。 @易卜拉欣 - mahrir – GKumar

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

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

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

試試這個代碼希望它值得您。

相關問題