繁体   English   中英

变量内的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”部分。 我尝试过各种方法,但是都没有用。

基本上与您发布的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放入其中。 但是,如果您需要“生成” JSON,则可能必须采用其他方法。

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

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

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

要么

metdata["art"] = art

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM