如何保留特定元素并删除json数组中的其他元素?
问题描述:
我有以下JSON数组:如何保留特定元素并删除json数组中的其他元素?
[
{ "id": "1", "title": "Pharmacy", "desc": "xyz"},
{ "id": "21", "title": "Engineering", "desc": "xyz"},
{ "id": "30", "title": "Agriculture", "desc": "xyz"},
...
]
我想只保留标题元素和删除等。我试图解决这个使用PHP和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);
或者,如果你想获得冠军的数组,并保持原有阵列不变:
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
答
在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);
答
在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
答
使用解决它在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
答
<?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'));
?>
试试这个代码希望它值得您。
如果你只保留一个属性,你可能会转换为一个字符串数组:'[“药房”,“工程”,“农业”,...]'。 – nnnnnn