我有一个 json,我必须从 json 对象中选择作者姓名,该对象不包含 available 作为其中的键
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
"available":false
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
},
"expensive": 10
}
那么,如果可以使用 jsonpath 或不可以,我该如何实现呢?
最佳答案
您可以过滤没有属性'available'
的书籍,然后通过过滤后的映射来获取作者姓名
const books = [
{
category: 'reference',
author: 'Nigel Rees',
title: 'Sayings of the Century',
price: 8.95
},
{
category: 'fiction',
author: 'Evelyn Waugh',
title: 'Sword of Honour',
price: 12.99,
available: false
},
{
category: 'fiction',
author: 'Herman Melville',
title: 'Moby Dick',
isbn: '0-553-21311-3',
price: 8.99
},
{
category: 'fiction',
author: 'J. R. R. Tolkien',
title: 'The Lord of the Rings',
isbn: '0-395-19395-8',
price: 22.99
}
]
const authorNames = books
.filter(book => !book.hasOwnProperty('available'))
.map(book => book.author)
console.log(authorNames)
引用
关于javascript - 如何根据key上的过滤器获取json路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63611402/