Ampersand in object's properties

会有一股神秘感。 提交于 2020-12-15 05:15:27

问题


I'm writing a JS script that has an object with &'s in some of its properties, e.g.

var topicObj = {
"Client & Peripherals": ["USB", "Printer", "Copy/Paste"],
"Install & Upgrade": ["Tenant Upgrade", "Agent upgrade"]
}

The thing is, when I attempt to iterate over one of its values, e.g.

selMTopic = "Client & Peripherals"
for (t in topicObj[selMTopic]) {
  addTopic(topicsDD,topicObj[selMTopic][t]);
}

it fails, it can't compute t, I guess it doesn't like having &'s, and similar characters, in the property.

I've been trying to find out how to have and use &'s in properties with no luck; I've tried encoding the string with encodeURIComponent but no luck either.

Any idea how can I do it, if possible? I need to have those &'s there. I'm thinking it using two arrays instead of the object, one with the object's properties, and the other each of the object's value arrays; but I would really rather stick with an object, as I may need to add more "levels of depth" in the future.


回答1:


use of (for array) instead of in (for properties)

var topicObj =
  { "Client & Peripherals" : ["USB", "Printer", "Copy/Paste"]
  , "Install & Upgrade"    : ["Tenant Upgrade", "Agent upgrade"]
  }
for (let selMTopic in topicObj)
  {
  for (let t of topicObj[selMTopic])
    {
    console.log( selMTopic,'->', t )
    // addTopic(topicsDD, t );
    }
  }


来源:https://stackoverflow.com/questions/64949836/ampersand-in-objects-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!