简体   繁体   中英

nodejs objects within variables

I'm unfamiliar with nodejs and javascript generally.

I have the following code which I need to pass as a variable within 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"
          }
        ]
      }
    }

I have so far been able to do this:

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

Which works, but I do not know how to then correctly pass the "art" and "backgroundImage" part. I have tried all kinds of things, but none of them have worked.

It is basically done the same way as the json data you posted

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'
            }
        ]
    }
};

Only difference is, that when you are defining your variable metadata you use = , but when you are dealing with properties within the object metadata (even if the properties themselves are objects), you use : to set them.

NodeJs accepts entire JSON object. So simply

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

Of course the other answers are correct in that you can simply put your JSON in there as in your example. But if you need to "generate" your JSON, then you might have to go a different way.

You generate the objects from "bottom" to "top" and just assign them to properties of your "parent" object.

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

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

or

metdata["art"] = art

I on purpose used different ways to write the different properties of the object to show you different ways to do this. They are all (more or less) equal end usage depends on your personal preference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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