在JavaScript属性过滤JSON数据 [英] Filter JSON data by property in JavaScript
问题描述
我有一个JSON序列集合:
[
{
_id:PERSON1
日期:2014年7月20日17点20分09秒,
listed_name:汤姆,
名:汤姆,
contact_info:tom@gmail.com
},
{
_id:PERSON2
日期:2014年7月20日17点20分09秒,
listed_name:珍,
名:简,
contact_info:Person2@gmail.com
},
{
_id:Person3可能,
日期:2014年7月20日17点20分09秒,
listed_name:约翰,
名:约翰,
contact_info:Person3@gmail.com
}
]
和属性名信息从另一页来了...
[_ ID,日期,listed_name]
该问题是...
使用JavaScript,我该如何使用第二个数组作为过滤器只返回包含在第二阵列中的列?
例如:使用此阵 [_ ID]
...这怎么阵列中使用,只显示 _id
的所有数据JSON对象,但保持了日期
, listed_name
,名称
,等...?
随着 [_ ID]
数组作为过滤器,预期的控制台输出应该是这样的:
PERSON1
PERSON2
Person3可能
假设你有你的传入的JSON在vairable ...
VAR parsedJSON = JSON.parse(inputJSON)
VAR filterArray = [_id,日期]对于(VAR I = 0; I< parsedJSON.length ++我){
对(在filterArray VAR的FilterItem){
的console.log(parsedJSON [I] [filterArray [的FilterItem]])
}
}
I have a JSON serialized collection:
[
{
"_id":"person1",
"date":"7/20/2014 17:20:09",
"listed_name":"Tom",
"name":"Tom",
"contact_info":"tom@gmail.com"
},
{
"_id":"person2",
"date":"7/20/2014 17:20:09",
"listed_name":"Jane",
"name":"Jane",
"contact_info":"Person2@gmail.com"
},
{
"_id":"person3",
"date":"7/20/2014 17:20:09",
"listed_name":"John",
"name":"John",
"contact_info":"Person3@gmail.com"
}
]
And property name information coming from another page...
["_id", "date", "listed_name"]
The questions is...
Using JavaScript, how can I use the second array as a filter to return only the columns contained in the second array?
For instance: using this array ["_id"]
... how can this array be used to only show the _id
data for all JSON objects but keep out date
, listed_name
, name
, etc...?
With the ["_id"]
array as a filter, the expected console output should look like this:
person1
person2
person3
Suppose you have your incoming JSON in a vairable...
var parsedJSON = JSON.parse(inputJSON)
var filterArray = ["_id","date"]
for(var i = 0;i< parsedJSON.length;++i){
for(var filterItem in filterArray){
console.log(parsedJSON[i][filterArray[filterItem]])
}
}
这篇关于在JavaScript属性过滤JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!