Reading an Order as an Object

Every label Marta prints starts the same way. She pastes an order from the shop platform into shipping_label.py, and the script reads it as a dict. Order 1042, two dotted A5 notebooks and a lined A6 for Iris Okafor in Leeds, is today’s first. Before the JavaScript port can pick an address or a postage rate, it needs that order in a form it can read.

In this lesson, you’ll write order 1042 as a JavaScript object, read its fields, and start a label by adding and removing keys. Reading a value by its key in square brackets works as in Python, and you’ll see why JavaScript also gives you a dot for it. Begin with the order itself.

Write the Order as an Object Literal

In the Python script, the order is a dict, with every key a quoted string and None where Iris left the shipping address empty because it’s the same as her billing address:

Language: Python
order = {
    "id": 1042,
    "billing_address": {
        "name": "Iris Okafor",
        "street": "12 Marsh Lane",
        "city": "Leeds",
        "postcode": "LS6 2QA",
        "country": "GB",
    },
    "shipping_address": None,
    "insured_value": 0,
    "line_items": [
        {"sku": "A5-DOT", "qty": 2},
        {"sku": "A6-LINED", "qty": 1},
    ],
    "tags": ["gift", "fragile", "gift"],
    "total": 46.0,
}

If you paste that into a JavaScript file, put const in front, and change None to null, it runs. Quoted keys are allowed in a JavaScript object literal, the curly-brace syntax for an object, which is JavaScript’s everyday key-value type. Each key-value pair in an object is called a property. JavaScript developers leave the quotes off the keys, though, as in this port:

Language: JavaScript
const order = {
  id: 1042,
  billing_address: {
    name: "Iris Okafor",
    street: "12 Marsh Lane",
    city: "Leeds",
    postcode: "LS6 2QA",
    country: "GB",
  },
  shipping_address: null,
  insured_value: 0,
  line_items: [
    { sku: "A5-DOT", qty: 2 },
    { sku: "A6-LINED", qty: 1 },
  ],
  tags: ["gift", "fragile", "gift"],
  total: 46.0,
};

Python needs the quotes because a bare word inside a dict literal is a variable, so {id: 1042} runs without an error and keys the dict by the built-in id() function. JavaScript reads a bare key in an object literal as the key’s own name, so id: 1042 makes a key called "id". Quotes are necessary only when a key isn’t a valid identifier, a name made of letters, digits, _, and $ that doesn’t start with a digit.

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.