【发布时间】:2017-04-04 07:34:31
【问题描述】:
我有一个如下的 JSON 数组:
[{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street":"201 S 4th St.",
"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":[
{
"books":"fiction",
"sports":"football",
"music":"rock"
},
{
"books":"action",
"sports":"cricket",
"music":"jazz"
},
{
"books":"action",
"sports":"cricket",
"music":"cool"
},
]},{
"id":2,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": ["1-770-736-8031 x56442", "4087917884", "4089088939"],
"website": "hildegard.org",
"dept":[{"name":"divya", "address":"abc"},{"name":"divya1", "address":"abc1"}],
"hobbies":[
{
"books":"fiction",
"sports":"football",
"music":"rock"
},
{
"books":"action",
"sports":"cricket",
"music":"jazz"
},
{
"books":"action",
"sports":"cricket",
"music":"cool"
},
]}]
我只想在爱好键中使用特定键。假设我只需要 Hobbies key 中的书籍和运动。我怎样才能在 Nodejs 中做到这一点? 结果应如下所示:
[{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street":"201 S 4th St.",
"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":[
{
"books":"fiction",
"sports":"football",
},
{
"books":"action",
"sports":"cricket",
},
{
"books":"action",
"sports":"cricket",
},
] },{
"id":2,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": ["1-770-736-8031 x56442", "4087917884", "4089088939"],
"website": "hildegard.org",
"dept":[{"name":"divya", "address":"abc"},{"name":"divya1", "address":"abc1"}],
"hobbies":[
{
"books":"fiction",
"sports":"football",
},
{
"books":"action",
"sports":"cricket",
},
{
"books":"action",
"sports":"cricket",
},
]}].
请注意,这只是一个示例。我的输入是一个 JSON 数组和我想要保留的键。此示例的键是“id”、“name”、“hobbies.books”、“hobbies.sports”等。
【问题讨论】:
-
无论如何,您都需要学习如何访问数组元素和对象属性。这归结为对 JavaScript 基础知识缺乏基本了解。
标签: javascript arrays json node.js underscore.js