问题
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