How do I assign value to KeyValue in script?

I have a KeyValue.. say

{ "Name": "misc 1", "SKU": "misc 2"}

I try to alter value using script, but below seems nothing work

keyValue1.data.Name.setAttribute("Name", "zzz");
keyValue1.data.Name.setData("Name", "zzz");
keyValue1.data.Name = "zzz";

Any help will be really grateful!

Hi and welcome to the forums,

It helps if you consider components like keyValue to be a "view only" type - you can view the data it's displaying but you don't alter it directly.
If you want to change the data its displaying, or you want the component to update when the underlying data changes, then you'll need to make it's data source dynamic, eg {{variable.value}} rather than hard code it into the component itself.
So that might be the result of a database select query, another component, a transformer, or any other output that you can manipulate and the component will automatically update.

Hi @dcartlidge

Thanks for the response, and the suggestion, as I can't find other example online, does that mean, I have to generate the JSON to serve as dynamic data source?

cheers.

I actually tried the below methods... but none work as well...

keyValue1.data = JSON.parse('{"Name": "123", "SKU": "zzz"}');

or

keyValue1.data.set ('string', '{"Name": "123", "SKU": "zzz"}');

Appreciate any help. Cheers.

Looks like you're still assigning a static value to the component, if you need the displayed values to update automatically you need to give the component a dynamic data value such as {{myquery.data}}
You don't have to tell the component to update, you tell the data that component is showing to update.
Here's a simple example
forum.json (13.1 KB)

1 Like

hi @dcartlidge

Thanks! I will try it out.

cheers.

Hi @dcartlidge

Got it to work finally, thanks for the help.