1. 程式人生 > >如何把物件轉換成陣列

如何把物件轉換成陣列

       Lodash是一個著名的javascript原生庫,不需要引入其他第三方依賴。是一個意在提高開發者效率,提高JS原生方法效能的JS庫。文件可通過官網下載,也可點此連結下載https://pan.baidu.com/s/1dFNYB8P(被吞了可以留言聯絡我)

      在lodash中有兩種物件轉換成陣列的方法,一種是使物件屬性值轉換成陣列,另一種是使物件的屬性名轉換成陣列。

一:_.values(使物件屬性值轉換成陣列)

_.values(object)

(Array): 返回物件屬性的值的陣列。

var items={"可口可樂":{"classification":"飲料","name":"可口可樂","unit":"瓶","price":"3","count":3,"subtotal":"6元(原價:    9元)","free_count":1,"free_money":3},"雪碧":{"classification":"飲料","name":"雪碧","unit":"瓶","price":"3","count":3,"subtotal":"6元(原價:    9元)","free_count":1,"free_money":3},"蘋果":{"classification":"水果","name":"蘋果","unit":"斤","price":"5.5","count":3,"subtotal":"16.5元","free_count":1,"free_money":3},"荔枝":{"classification":"水果","name":"荔枝","unit":"斤","price":"2","count":3,"subtotal":"6元","free_count":1,"free_money":3},"電池":{"classification":"生活用品","name":"電池","unit":"個","price":"15","count":2,"subtotal":"30元","free_count":1,"free_money":3},"方便麵":{"classification":"食品","name":"方便麵","unit":"袋","price":"4.5","count":2,"subtotal":"9元","free_count":1,"free_money":3}}
_.values(items)//[{"classification":"飲料","name":"可口可樂","unit":"瓶","price":"3","count":3,"subtotal":"6元(原價:    9元)","free_count":1,"free_money":3},{"classification":"飲料","name":"雪碧","unit":"瓶","price":"3","count":3,"subtotal":"6元(原價:    9元)","free_count":1,"free_money":3},{"classification":"水果","name":"蘋果","unit":"斤","price":"5.5","count":3,"subtotal":"16.5元","free_count":1,"free_money":3},{"classification":"水果","name":"荔枝","unit":"斤","price":"2","count":3,"subtotal":"6元","free_count":1,"free_money":3},{"classification":"生活用品","name":"電池","unit":"個","price":"15","count":2,"subtotal":"30元","free_count":1,"free_money":3},{"classification":"食品","name":"方便麵","unit":"袋","price":"4.5","count":2,"subtotal":"9元","free_count":1,"free_money":3}]

二:_.keys(使物件的屬性名轉換成陣列)

 _.keys(object)

返回(Array): 返回包含屬性名的陣列。

var items={"可口可樂":{"classification":"飲料","name":"可口可樂","unit":"瓶","price":"3","count":3,"subtotal":"6元(原價:    9元)","free_count":1,"free_money":3},"雪碧":{"classification":"飲料","name":"雪碧","unit":"瓶","price":"3","count":3,"subtotal":"6元(原價:    9元)","free_count":1,"free_money":3},"蘋果":{"classification":"水果","name":"蘋果","unit":"斤","price":"5.5","count":3,"subtotal":"16.5元","free_count":1,"free_money":3},"荔枝":{"classification":"水果","name":"荔枝","unit":"斤","price":"2","count":3,"subtotal":"6元","free_count":1,"free_money":3},"電池":{"classification":"生活用品","name":"電池","unit":"個","price":"15","count":2,"subtotal":"30元","free_count":1,"free_money":3},"方便麵":{"classification":"食品","name":"方便麵","unit":"袋","price":"4.5","count":2,"subtotal":"9元","free_count":1,"free_money":3}}
_.keys(items)//["可口可樂","雪碧","蘋果","荔枝","電池","方便麵"]