πŸ‘€ Our most exciting product launch yet πŸš€ Join us May 8th for Sanity Connect

How to Remove a Reference from an Array of References

4 replies
Last updated: Apr 14, 2022
Hi everyone. I am struggling to remove references from an array of references. The array contains up to three references with the same ID.I am only able to remove everyone with the same ID, or no one at all.
This removes all with the defined ID.

const action = unset(

[{_ref: cardId}]

);

onChange(PatchEvent.from(action));

}
Is it possible to remove only one instance? By querying all instances of an ID in an array, and target the first in that list for example? Something like this:

const action = unset(

[{_ref: cardId}][0]

);

onChange(PatchEvent.from(action));

}

Thanks!
Apr 13, 2022, 9:40 PM
Hi
user M
that is correct. I'm making a deck builder, and it's allowed to have up to three of the same card in a deck
Apr 13, 2022, 11:14 PM
I tried the following code as well, but it's the same result:

const action =
`unset([
cardSelection[_ref == ${cardId}]
])`
onChange(PatchEvent.from(action));

}
Apr 13, 2022, 11:30 PM
Hmm, that is a tough one since it's going to unset anything in that array that matches that card id. I wonder if using the client to perform a patch instead of PatchEvent could give you more flexibility? But then you'd be introducing something that could possibly impact performance.
Can you maybe just use more complex logic when determining what to unset? Or possibly use the index of the item you're unsetting instead of the id? If you share your code I could play around with it.
Apr 13, 2022, 11:40 PM
Thanks for your thoughts
user M
. I solved it by rewriting how the keys are generated. They match with the number clicked. So to remove one or more cards, I just target the key. Works perfectly.
1:{} 3 items
 _ref:01026
 _type:reference
 _key:01026-1
2:{} 3 items
 _ref:01026
 _type:reference
 _key:01026-2
I remove references with the following code:


let i = value

do {

i--

const action = unset(
`[{ _key:
${cardId}-${i + 1}
}]`
);

onChange(PatchEvent.from(action));

} while (i > number);
Apr 14, 2022, 7:33 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?