Skip to content

How to add a [key: alias] node to a map? #470

Answered by slhck
slhck asked this question in Q&A
Discussion options

You must be logged in to vote

Thanks, I figured that I'd need it, but the exact steps required weren't obvious for me from the given examples.

After fumbling around a lot, here is the simplest way I found to create a new alias:

const document = YAML.parseDocument('foo: bar');
const foo = document.get('foo', true);

if (isScalar(foo)) {
  foo.anchor = 'foo_anchor';
  const alias = document.createAlias(foo);
  document.add({ key: 'foo_alias', value: alias });
}

expect(document.toString()).toContain('foo: &foo_anchor');
expect(document.toString()).toContain('foo_alias: *foo_anchor');

Here is the fully working example from the original question — note that I forced casts of the return values from .get which is not recomm…

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@slhck
Comment options

@eemeli
Comment options

@slhck
Comment options

Answer selected by slhck
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants