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

问题描述

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

我有什么:

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

我需要什么:

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',{ action_type: 'landing_page_view',value: '5' }
]

console.log(actions.map((item)=> ({[item.action_type]: item.value})))