【问题标题】:nodejs objects within variables变量中的nodejs对象
【发布时间】:2018-11-13 20:00:32
【问题描述】:

我一般不熟悉nodejs和javascript。

我有以下代码需要在 nodejs 中作为变量传递:

"metadata": {
      "title": "title of the track to display",
      "subtitle": "subtitle of the track to display",
      "art": {
        "sources": [
          {
            "url": "https://url-of-the-album-art-image.png"
          }
        ]
      },
      "backgroundImage": {
        "sources": [
          {
            "url": "https://url-of-the-background-image.png"
          }
        ]
      }
    }

到目前为止,我已经能够做到这一点:

var metadata = { 
    "title": "title of the track to display",
    "subtitle": "subtitle of the track to display"
    };

哪个有效,但我不知道如何正确传递“艺术”和“背景图像”部分。我尝试了各种方法,但都没有奏效。

【问题讨论】:

    标签: node.js var


    【解决方案1】:

    基本上和你发布的json数据是一样的

    const metadata = {
        title: 'title of the track to display',
        subtitle: 'subtitle of the track to display',
        art: {
            sources: [
                {
                    url: 'http://url-of-the-album-art-image.png'
                }
            ]
        },
        backgroundImage: {
            sources: [
                {
                    url: 'https://url-of-the-background-image.png'
                }
            ]
        }
    };
    

    唯一的区别是,当您定义变量metadata 时,您使用=,但是当您处理对象metadata 中的属性时(即使属性本身是对象),您使用@987654325 @ 设置它们。

    【讨论】:

    • 这是有效的解决方案,谢谢。我确定我试过了,但我使用的是 var metadata = 而不是 const metadata =
    【解决方案2】:

    NodeJs 接受整个 JSON 对象。就这么简单

    var metadata = {
          "title": "title of the track to display",
          "subtitle": "subtitle of the track to display",
          "art": {
            "sources": [
              {
                "url": "https://url-of-the-album-art-image.png"
              }
            ]
          },
          "backgroundImage": {
            "sources": [
              {
                "url": "https://url-of-the-background-image.png"
              }
            ]
          }
        }
    

    【讨论】:

      【解决方案3】:

      当然,其他答案是正确的,因为您可以像示例中那样简单地将 JSON 放入其中。但是,如果您需要“生成”您的 JSON,那么您可能必须采用不同的方式。

      您从“底部”到“顶部”生成对象,并将它们分配给“父”对象的属性。

      var sources = [
            {
              "url": "https://url-of-the-background-image.png"
            }
          ]
      
      var art = {sources: sources}
      metadata.art = art
      

      metdata["art"] = art
      

      我故意使用不同的方式来编写对象的不同属性,以向您展示不同的方式来做到这一点。它们都(或多或少)相同的最终用途取决于您的个人喜好。

      【讨论】:

        猜你喜欢
        • 2018-04-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-31
        • 1970-01-01
        • 2019-07-27
        • 2012-08-26
        • 1970-01-01
        相关资源
        最近更新 更多