jslt icon indicating copy to clipboard operation
jslt copied to clipboard

How to push elements to an array

Open AnupKumarPanwar opened this issue 3 years ago • 6 comments

I want to keep a track of visited productIds in an array. How do I push elements to an array?

I've tried the following code but it is not working.

let visitedProductIds = [1,2,3]
$visitedProductIds = $visitedProductIds + [4,5,6]

{
    "visited": $visitedProductIds
}

AnupKumarPanwar avatar Feb 23 '23 13:02 AnupKumarPanwar

You can't. This is a functional language, so you can't change values. You can build new ones, but you can't change the ones that already exist.

You need to do something like this:

{
    "visited": <expression that computes visited product ids>
}

Now I don't understand what "visited" means in this context, but maybe something like this?

let visitedProducts = <whatever you do to make that list>

{
  "visited" : [for ($visitedProducts) .id], // or something like that
  "products" : $visitedProducts, // or something like it
}

I hope this helps.

larsga avatar Feb 23 '23 13:02 larsga

Hello, i am newbie in jslt. I don't know how to transform this type of array of json in jslt. Please i would need your help. My input json is : { "test1" : "test output1", "Details" : { "0" : { "id" : "first" }, "1" : { "id" : "second" } } }

And my desired output is this. { “Details” : { “0” : { “id” : “first”, “test1" : “test output1” }, “1" : { “id” : “second”, “test1” : “test output1" } } }

oyeyemi avatar May 20 '23 06:05 oyeyemi

This is a new question, so it would be better to make a new issue for it. I'll answer you here anyway.

It's a bit difficult to tell what rules you want to follow here, but I'll make a guess. Maybe like this?

let obj = .
{
  "Details" : {for (.Details)
    .key : .value + {"test1" : $obj.test1}
  }
}

larsga avatar May 20 '23 09:05 larsga

Thank you so much for answering my question despite posted to the wrong place. I noticed this part (+ {"test1" : $obj.test1}) did the trick. Please, can you kindly explain it to me in brief. Thanks for your help.

oyeyemi avatar May 20 '23 10:05 oyeyemi

Using + with two objects merges the two objects into one. Try it out in the playground and you'll see.

larsga avatar May 20 '23 10:05 larsga

Thank you for the explanation. I am on playground already. I also noticed it's appending comma(,) separator automatically.

oyeyemi avatar May 20 '23 11:05 oyeyemi