簡體   English   中英

如何使用鍵值對在 javascript 中轉換 object

[英]how to transform object in javascript using key value pair

我需要一些幫助來操作 object。

我有的:

 actions: [
    { action_type: 'comment', value: '1' },
    { action_type: 'link_click', value: '5' },
    { action_type: 'post_reaction', value: '1' },
    { action_type: 'landing_page_view', value: '5' },

我需要的:

actions: [
    { comment : 1 },
    { link_click : 5 },
    { post_reaction : 1 },
    { landing_page_view : 5 },

我怎樣才能做到這一點? 在此先感謝您的幫助::)

const newActions = actions.map((item)=> ({[item.action_type]: item.value}))

如果您的道具名稱不會改變,您可以使用array.map ,( array.map通過將每個元素轉換為新形式來創建新數組):

actions.map(a => ({[a.action_type]: a.value})

可以使用obj[myKey]之類的字符串索引來訪問對象的 props,因此您可以使用action[i].action_type作為新 object 中的鍵。

您可以使用 map

 const actions = [ { action_type: 'comment', value: '1' }, { action_type: 'link_click', value: '5' }, { action_type: 'post_reaction', value: '1' }, { action_type: 'landing_page_view', value: '5' } ] console.log(actions.map((item)=> ({[item.action_type]: item.value})))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM