我正在尝试从 JavaScript 对象中组装某个字符串,但遇到了一些问题。
我创建了一个接受对象并返回字符串的函数。初始对象如下所示:
var testObject = {
"Topics": ["Other", "New1"],
"Other": ["try this", "this also"]
};
我希望字符串吐出这样的内容:
"Topics~~Other|Topics~~New1|Other~~try this|Other~~this also"
这是我现在拥有的:
var testObject = {
"Topics": ["Other", "New1"],
"Other": ["try this", "this also"]
};
function transformObjectToString(activeFilters) {
var newString = "";
var checkFilterGroups = function(filterTopic) {
activeFilters[filterTopic].map(function(selectedFilter) {
var tempString = filterTopic + "~~" + selectedFilter + "|";
console.log("check string", tempString);
newString.concat(tempString);
});
}
for (var filterGroup in activeFilters) {
checkFilterGroups(filterGroup);
}
return newString;
}
console.log(transformObjectToString(testObject));
当我检查日志时,临时字符串的格式似乎正确,但是,无论出于何种原因,concat
似乎没有像我想象的那样工作。
最佳答案
您应该能够只使用 +=
因为这只是字符串连接。然后,您所要做的就是删除最后一个字符。这是一个带有更改的 JSFiddle https://jsfiddle.net/tfs98fxv/37/ .
关于javascript - 在 JavaScript 中从对象创建字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34541243/