【问题标题】:Relation between two JSONs through keys两个 JSON 之间通过键的关系
【发布时间】:2018-12-13 15:13:54
【问题描述】:

所以我有 2 个不同的 JSON。 书籍

{
  "books": [{
    "name": "Lord of the rings",
    "author": 1,
    "year": 1937,
    "genre": 3,
    "imageUrl": "https://cdn.lifehack.org/wp-content/uploads/2015/03/9780618640157_custom-s6-c30.jpg",
    "availability": true
  }]
}

还有一个,作者

{
  "authors": [{
    "id": 1,
    "name": "J.R.R. Tolkien"
  }, {
    "id": 2,
    "name": "Harper Lee"
  }, {
    "id": 3,
    "name": "J.K. Rowling"
  }]
}

我想让作者像一个 id,所以当我显示一本书的作者时,我想要的是名字(在第二个 json 中),而不是 id。 我怎样才能做到这一点? 不确定是否重要,但我在 VUE 工作。

【问题讨论】:

    标签: json vue.js key


    【解决方案1】:

    您可以使用 loash 的 find 方法来执行此操作,例如

    文档:https://lodash.com/docs/4.17.11#find

    _.find(authors, { 'id': 1 });
    

    【讨论】:

      【解决方案2】:

      我会使用原生的 Array.filter 方法,如下所示:

      let tolkien = authors.filter(author => !!author.id === 1)
      

      使用 .filter 意味着您不需要为这个方法包含像 lodash 这样的库。

      【讨论】:

        【解决方案3】:

        您可以创建一个新对象,其键映射到作者(即author[1] = {id: 1, ...}),这将使您可以通过他/她的 id 快速轻松地访问任何作者。示例:

        let authorByIds = {};
        authors.forEach(author => {
            authorByIds[author.id] = {...author};
        });
        
        let firstBook = books[0];
        
        console.log(authorByIds[firstBook.author]);
        // will output author with id = 1, i.e J.R.R. Tolkien
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多