【问题标题】:How to interpolate a key based on a parameter and update its value in an object es6如何根据参数插入键并在对象 es6 中更新其值
【发布时间】:2021-02-08 18:15:35
【问题描述】:

我有

const abc = {
  main: {
    primary: 'initialPrimary',
    },
  buttons: {
    text: 'initialText',
  },
}
const updateAbc = (node, key, value) => {
return {updated abc}
}

所以,如果我调用updateAbc('main','primary','updatedPrimary'),它应该返回更新后的 abc 对象

{
  main: {
    primary: 'updatedPrimary',
   },
  buttons: {
    text: 'initialText',
  },
}

或者当调用updateAbc('buttons','text','updatedText')时,它应该返回更新后的带有值的abc对象

{
  main: {
    primary: 'initialPrimary',
  },
  buttons: {
    text: 'updatedText',
  },
}

它应该只更新传递的值。在 es6 中如何实现?

【问题讨论】:

标签: javascript reactjs ecmascript-6


【解决方案1】:
const abc = {
  main: {
    primary: 'initialPrimary',
    },
  buttons: {
    text: 'initialText',
  },
}

const updateAbc = (node, key, value) => {
  return {
     ...abc, 
    [node]: {
      [key]: value
    } 
  }
}

请注意,这不会按原样检查不存在的节点或键。

您专门要求 es6,所以这就是我的回答。这通过传播abc,然后动态使用node 和key 来提供更新值的路径。

通过使用Object.assign,您可以通过以下方式获得相同的结果:

const updateAbc = (node, key, value) => {
  var copyAbc = Object.assign({},abc)
  copyAbc[node][key] = value
  return copyAbc
}

但是如果给定一个不存在的 node 名称,则会失败并产生错误

【讨论】:

    猜你喜欢
    • 2022-12-01
    • 2021-11-04
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 2019-06-14
    相关资源
    最近更新 更多