javascript - 如何根据key上的过滤器获取json路径?

标签 javascript json jsonpath

我有一个 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)


引用

Object.prototype.hasOwnProperty()

关于javascript - 如何根据key上的过滤器获取json路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63611402/

相关文章:

asp.net - 不使用 AJAX 加载图像

javascript - 使用 fadeIn() 和 fadeOut() 来动画 AJAX 响应

json - 如何使用 @JsonManagedReference 和 @JsonBackReference 映射 POJO 之间的 OneToOne 关系

kubernetes 打印特定列

javascript - 使用 javascript 删除主页内容

javascript - 传递一个mocha-before中生成的值给express app

php - 如何在 JSON 中添加 JSON 数组名称

JAVA获取嵌套在JSONObject中的Byte[]

JSON 解析器 -java.lang.NoSuchFieldError : defaultReader

c# - 使用 Json.NET 选择特定对象(SelectToken)