Java script extract all values from a map in an array

Viewed 256

Using spring boot,I get a list from the backend,so in HTML:

<script th:inline="javascript">
   var test = [[${productRecords}]];
</script>

By viewing the page source, I found it gives me:

<script th:inline="javascript">
       var test [{"productid":1,"productname":"nail","productcosttime":null,"img":null,"counts":8,"bookings":[]},{"productid":2,"productname":"hairWash","productcosttime":null,"img":null,"counts":40,"bookings":[]},{"productid":7,"productname":"jiemao","productcosttime":null,"img":null,"counts":1,"bookings":[]},{"productid":6,"productname":"makeUp","productcosttime":null,"img":null,"counts":1,"bookings":[]}];
</script>

Now I want to extract all the 'productid' and 'counts', and assign them to new variables conrespondingly, like

var productid = [1,2,7,6]
var counts = [8,4-,1,1]

How could I achieve this?

I have tried:

var temp = test[0].productid;
2 Answers

You can extract object properties using map function

let productids = test.map(obj => obj.productid) //[1,2,7,6]
let count_result = test.map(obj => obj.counts)  //[8,4-,1,1]

You can also accomplish this with Thymeleaf if you want (I think the JavaScript is fine as well, just another tool you can use).

let productid = [[${productRecords.![productid]}]];
let counts = [[${productRecords.![counts]}]];

See collection projection.

Related