[英]extracting values from json using Underscorejs
我有一個JSON從中我需要篩選其的對象name
值所傳遞的輸入相匹配,然后摘去href
值從相應的links
對象具有ref
的值self
。 我將附加代碼段以及我的過濾方法。 我正在使用Underscore.js
。
var jsonObj = [
{
"links": [
{
"rel": "self",
"href": "http://hostname:port/state/644444",
"variables": [],
"variableNames": [],
"templated": false
},
{
"rel": "city",
"href": "http://hostname:port/city/6184",
"variables": [],
"variableNames": [],
"templated": false
}
],
"stateId": 65986,
"countyId": 6184,
"name": "AAATest",
"population": 20000,
"location": "SFS CSR"
},
{
"links": [
{
"rel": "self",
"href": "http://hostname:port/state/65987",
"variables": [],
"variableNames": [],
"templated": false
},
{
"rel": "city",
"href": "http://hostname:port/city/6184",
"variables": [],
"variableNames": [],
"templated": false
}
],
"stateId": 65987,
"countyId": 6184,
"name": "2k8std511",
"population": 20000,
"location": "SFS CSR"
}
]
var keywords='2k8std511';
var filtered = _.filter(jsonObj, function (item) {
return (_.contains('2k8std511', item['name']));
});
console.log(_.chain(jsonObj)
.pluck("links")
.flatten()
.value());
請讓我知道如何根據給定的關鍵字進行過濾:
輸入示例: AAATest
預期輸出:[href:' http://主機名:端口/狀態/ 644444 ']
問候,Pradeep
您可以使用簡單的JavaScript來做到這一點:
var result = jsonObj.filter(function(obj) {
return obj.name === 'AAATest'
}).reduce(function(acc, obj) {
var links = obj.links.filter(function(link) {
return link.rel === 'self'
}).map(function(link) {
return link.href
})
return acc.concat(links)
},[])
console.log(result) //=> ["http://hostname:port/state/644444"]
下划線解決方案:
var jsonObj = [{ "links": [{ "rel": "self", "href": "http://hostname:port/state/644444", "variables": [], "variableNames": [], "templated": false }, { "rel": "city", "href": "http://hostname:port/city/6184", "variables": [], "variableNames": [], "templated": false }], "stateId": 65986, "countyId": 6184, "name": "AAATest", "population": 20000, "location": "SFS CSR" }, { "links": [{ "rel": "self", "href": "http://hostname:port/state/65987", "variables": [], "variableNames": [], "templated": false }, { "rel": "city", "href": "http://hostname:port/city/6184", "variables": [], "variableNames": [], "templated": false }], "stateId": 65987, "countyId": 6184, "name": "2k8std511", "population": 20000, "location": "SFS CSR" }] var filtername = 'AAATest'; var answer = _.chain(jsonObj) .filter(function(obj) { return obj.name === filtername; }) .map(function(obj) { return obj.links }) .first() .filter(function(obj) { return obj.rel === 'self' }) .map(function(obj) { return obj.href }) .value(); console.log(answer);
<script src="http://underscorejs.org/underscore-min.js"></script>
使用下划線的另一個版本:
var result = _.chain(jsonObj)
.where({ name: 'AAATest' })
.pluck('links')
.flatten()
.where({ rel: 'self'})
.pluck('href')
.value();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.