变量中的nodejs对象

nodejs objects within variables

我不熟悉 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"
    };

有效,但我不知道如何正确传递 "art" 和 "backgroundImage" 部分。我尝试了各种方法,但 none 的方法都奏效了。

基本上与您发布的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(即使属性本身是对象),您使用 : 来设置它们。

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"
          }
        ]
      }
    }

当然,其他答案是正确的,因为您可以像示例中那样简单地将 JSON 放在那里。但是,如果您需要 "generate" 您的 JSON,那么您可能需要采用不同的方式。

您生成从 "bottom" 到 "top" 的对象,然后将它们分配给 "parent" 对象的属性。

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

var art = {sources: sources}
metadata.art = art

metdata["art"] = art

我故意使用不同的方式来编写对象的不同属性,以向您展示执行此操作的不同方法。它们都是(或多或少)相同的最终用途取决于您的个人喜好。