假设我有一个JSON对象数组,如下所示:
[{ "id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
},
"hobbies":['cricket', 'football']},{
"id": 2,
"name": "Graham",
"username": "David",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "San Jose",
"zipcode": "92998-3874",
"geo": {
"lat": "39.3159",
"lng": "121.1496"
}
},
"phone": ["1-770-736-8031 x56442", "4087917884", "4089088939"],
"website": "hildegard.org",
"dept":[{"name":"divya", "address":"abc"},{"name":"divya1", "address":"abc1"}],
"hobbies":['baseball']}]
现在我想根据特定键获取数据,键也可以是嵌套键。让我们举一个例子,我只想获得这些密钥的数据:'name','username','city','lat','lng'。所以输出结果如下:
[{
name:'Leanne Graham',
username:'Bret',
address.city:'Gwenborough',
address.geo.lat:"-37.3159",
address.geo.lng: "81.1496"
},
{
name:'Graham',
username:'David',
address.city:'San Jose',
address.geo.lat:"39.3159",
address.geo.lng: "121.1496
}]
任何人都可以告诉我如何在NodeJS上执行此操作吗?
答案 0 :(得分:-1)
如果您愿意安装依赖项,则可以查找lodash.get
;
npm i --save lodash.get
这将允许您:
const _get = require('lodash.get');
_get(obj, 'address.city'); // "San Jose"
使用此实用程序,您可以更轻松地查询对象的特定键/值,并根据您的要求组合自定义对象。
否则,您可以创建自己的安全访问器功能:
function getKey(key, obj) {
return key.split('.').reduce(function(a,b){
return a && a[b];
}, obj);
}
getKey('address.city'', obj); // "San Jose"
答案 1 :(得分:-1)
执行复杂数据查询的最简单方法是依赖数据存储引擎,该引擎支持足够丰富的查询语言以满足您的需求。 Mongo,Couchbase和Elasticsearch是内置全功能查询语言的存储引擎示例。
另一种方法是使用像Lodash或Ramda这样的函数库来构建数据提取管道。
使用Lodash从您提供的数据示例中提取:
const _ = require('lodash')
// paths to extract from matching records
const field_paths = [
'name',
'username',
'address.city',
'address.geo.lat',
'address.geo.lng']
// extract value at field_paths and add to result
const extract_fields = (rec) => {
let res = {}
field_paths.forEach((path) => {
res[path] = _.get(rec, path)
})
return res
}
// query for all records where
// name is like "*Graham*" irrespective of letter case.
//
// and extract required fields from matching records
const results = _(data)
.filter((rec) => _.get(rec, 'name').match(/\bgraham\b/i))
.map(extract_fields)
.value()
console.log(results)
将打印:
[ { name: 'Leanne Graham',
username: 'Bret',
'address.city': 'Gwenborough',
'address.geo.lat': '-37.3159',
'address.geo.lng': '81.1496' },
{ name: 'Graham',
username: 'David',
'address.city': 'San Jose',
'address.geo.lat': '39.3159',
'address.geo.lng': '121.1496' } ]