0

So I am creating an object in a cell in a quarto-file like this:

```{ojs}
{
{
  const persons = {
    mike: {
      age: 32,
      height: 180,
    },
    anna: {
      age: 32,
      height: 175,
    },
  };
}
}
```

I then want to use it in another cell like this:

```{ojs}
console.log("persons: ", persons)
```

Yet I get this error:

OJS Runtime Error: "persons is not defined"

I'm not really sure how I could use the data in a subsequent cell...

tarleb
  • 19,863
  • 4
  • 51
  • 80
Lenn
  • 1,283
  • 7
  • 20

2 Answers2

1

Here in this Observable document, it states that variable scope is local to the cell they are defined in. You can instead use a block statement in which you return an object. (Reference: https://observablehq.com/@observablehq/observables-not-javascript#block)

persons = {
  return {
    mike: {
      age: 32,
      height: 180,
    },
    anna: {
      age: 32,
      height: 175,
    },
  };
}

And in other cell, just use the block statement name:

persons

A small demo here: https://observablehq.com/d/a11ea84988aced36

This is different from how you are using this, but I hope it helped.

Aastha Bist
  • 324
  • 2
  • 11
1

I think Aastha’s answer should work, but it can be more concise. In Observable, if you want define a cell as an object literal, you can enclose the top-level curly braces in parentheses:

persons = ({
  mike: {
    age: 32,
    height: 180
  },
  anna: {
    age: 32,
    height: 175
  }
})

If you just do the curly braces, Observable expects a function body, e.g. with a return statement. And, as Aastha showed, you can't use “const” or “let” or “var” for a cell definition, just name =.

Toph
  • 2,561
  • 2
  • 24
  • 28