如何使用键值对转换 javascript 中的对象

how to transform object in javascript using key value pair

我需要一些帮助来操作对象。

我有:

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

对象的 props 可以使用像 obj[myKey] 这样的字符串索引来访问,因此您可以使用 action[i].action_type 作为新对象的键。

您可以使用地图

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