Adding a new entry (key and value) to a collection / object

The result of $entry->locator()->toLocation(); is not a collection object but a Kirby\Cms\StructureObject object, i.e. a single element in a Kirby\Cms\Structure Object.

And if you call $location->content() you end ob with a Kirby\Cms\Content object, which is not a collection type object either.

In general, objects are immutable in Kirby, which means they cannot be changed. But of course, you can create new objects, for example:

  $location = $entry->locator()->toLocation();
  // get the content object from the StructureObject object and convert to array
  $content = $location->content()->toArray();
  // add an item to the array
  $content['mykey'] = 'somekey';
  dump($content);
  // create new content object from that array
  $content = new Kirby\Cms\Content($content);
  dump($content);
  // then you can echo the field object like normal
  echo $content->mykey();

If this has any advantage for your use case over just using the array, that's something you have to decide.