1

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 2

1

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]
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.