Writing Javascript data objects for beginners

- Posted in javascript

There is a difference between JS data objects and JSON, but let’s not go into that for the purposes of this post.

Let’s keep it simple.

Create a new text file. Open 2 square brackets (create an array).

[

]

Start an object:

[
    {
    
    }
]

Within the object, set a key and a value.

[
    {
        "title": "My title"
    }
]

Repeat your object if you want multiple entries:

[
    {
        "title": "My title"
    },
    {
        "title": "My title 2"
    }
]

Let’s go back to 1 entry to make this shorter, and let’s add some more properties.

[
    {
        "title": "My title",
        "date": "September 27, 2019",
        "content": "My blog post content"
    },
]

Now let’s go back to 2 entries to have a logical endpoint to “loop over”.

[
    {
        "title": "My title",
        "date": "September 27, 2019",
        "content": "My blog post content"
    },
    {
        "title": "My title 2",
        "date": "September 29, 2019",
        "content": "My blog post content 2"
    },
]

Now you can use this object over in various templating languages or just using plain Javascript.

Here’s an example of a loop with this data object in the Svelte REPL.

Here’s a Codepen using Pug.

Leave a Reply

Your email address will not be published. Required fields are marked *