【问题标题】:How to create a Javascript object with index and values with variables?如何使用变量创建具有索引和值的 Javascript 对象?
【发布时间】:2020-03-17 22:08:25
【问题描述】:

我的 javascript 代码有问题,我需要创建一个带有变量的对象,而这些变量也是对象。说明:

我的 javascript 代码中需要这个(类似于 Json 结构):

var myObj = {
   variableOne: {
             variableOneA: 'someValue',
             variableOneB: 'someValue'
         }
   variableTwo: {
             variableTwoA: 'someValue',
             variableTwoB: 'someValue'
         }
   variableThree: {
             variableThreeA: 'someValue',
             variableThreeB: 'someValue'
         }
 }

现在,我的问题是在 Js 中我不能对对象执行“推送”方法,我只能向对象添加一级变量:

myObj.variableOne = 'someValue';

谁能帮帮我?我相信解决方案可能很容易,但我是 Js 的新手。

【问题讨论】:

  • myObj.variableOne.variableOneA = 'someValue' - 你的意思是这样吗?您可以使用. 字符访问每个更深层次。或者,如果它是一个列表,为什么不使用数组呢? myObj.variableOne = ['someValue', 'someValue']
  • 您可以将新对象分配给属性:myObj.variableOne = {variableOneA:"somevalue"}。你可以让它变得像你想要的那样复杂。实际上我们的第一个 sn-p 是有效的 js,它会给你一个具有所需结构的对象
  • 您究竟希望“推送到对象”做什么,自动创建该对象并将someValue 放入variableOneA 中?如果是,那么如果您没有在任何地方指定名称属性variableOneA,它如何知道它?

标签: javascript arrays object vue.js ecmascript-6


【解决方案1】:

在 Javascript 中有多种访问对象的方法。

var myObj = {
   variableOne: {
             variableOneA: 'oneA',
             variableOneB: 'oneB'
         }
   variableTwo: {
             variableTwoA: 'twoA',
             variableTwoB: 'twoB
         }
   variableThree: {
             variableThreeA: 'threeA',
             variableThreeB: 'threeB'
         }
 }

您可以使用“点”来访问对象的特定级别。

const valueVariableOneA = myObj.variableOne.variableOneA
console.log(valueVariableOneA) // output => "oneA"

您可以使用方括号代替点。当您想用破折号创建对象的键时,方括号很有用(例如:“cool-key”)

const valueVariableThreeB = myObj['variableThree']['variableThreeB']
console.log(valueVariableThreeB) // output => "threeB"

您还可以使用解构来访问特定值

// Get value of variableTwoA key

const { variableTwoA } = myObj.variableTwo // first way
const { variableTwo : { variableTwoA } } = myObj // second way

console.log(variableTwoA) // output => "twoA"

现在要向嵌套对象添加 key,您可以使用点或方括号方法。下面介绍如何在第一级添加密钥。

myObj.variableFour = { variableFourA: 'fourA', variableFourB: 'fourB' }
myObj['variableFour'] = { variableFourA: 'fourA', variableFourB: 'fourB' }

// add key on nested object

myObj.variableOne.variableOneC = 'oneC'
myObj['variableOne']['variableOneC'] = 'oneC'

// you can mix both
myObj['variableOne'].variableOneC = 'oneC'
myObj.variableOne['variableOneC'] = 'oneC'

【讨论】:

  • 非常感谢,就这样!!
【解决方案2】:

使用此代码:

myObj.variableOne['someValue'] = 'new value';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-23
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 2012-03-13
    • 2020-06-25
    • 2011-03-21
    • 1970-01-01
    相关资源
    最近更新 更多