简体   繁体   中英

Java script extract all values from a map in an array

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;

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM