简体   繁体   English

Java 脚本从数组中的 map 中提取所有值

[英]Java script extract all values from a map in an array

Using spring boot,I get a list from the backend,so in HTML:使用 spring 启动,我从后端得到一个列表,所以在 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现在我想提取所有的“productid”和“counts”,并将它们相应地分配给新变量,比如

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您可以使用map function 提取 object 属性

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).如果需要,您也可以使用 Thymeleaf 来完成此操作(我认为 JavaScript 也很好,只是您可以使用的另一个工具)。

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

See collection projection .请参阅集合投影

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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