java脚本从数组中的Map中提取所有值

qacovj5a  于 2021-07-13  发布在  Java
关注(0)|答案(2)|浏览(280)

使用spring boot,我从后端获得一个列表,因此在html中:

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

通过查看页面源代码,我发现它提供了:

<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>

现在我想提取所有的'productid'和'counts',并相应地将它们赋给新变量,如

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

我怎样才能做到这一点?
我试过:

var temp = test[0].productid;
unftdfkk

unftdfkk1#

可以使用Map函数提取对象属性

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

xoefb8l82#

如果您愿意,您也可以使用thymeleaf来实现这一点(我认为javascript也不错,只是您可以使用的另一个工具)。

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

请参见集合投影。

相关问题