我有一个对象,在某些时候有四个级别深,但是我想要一个能够应对引入更多级别的函数。我正在尝试编写一个函数来替换元素,例如 <span class="ajax-parent1-parent2-parent3-value"></span>
将替换为 parent1.parent2.parent3.value
。
问题是深度是可变的,所以我可以有类似 <span class="ajax-parent1-value"></span>
的东西替换为parent1.value
。
最后,并不总是要替换的文本。可选地,data-attr
可以指定要使用的属性(通过 element.attr(<data-attr>, <value>)
)。
目前,我正在手动迭代,但是它不是很干净,所以我想知道是否有更好的方法来做到这一点。这对于深度超过两层的情况也不起作用。
function render(data) {
$.each(data, function(parent, value) {
$.each(value, function(element, value) {
$el = $('.ajax-' + parent + '-' + element);
$.each($el, function(key, el) {
if ($(el).data('attr')) {
$(el).attr($(el).data('attr'), value);
} else {
$(el).text(value);
}
}
});
});
}
示例对象:
{
"profile": {
"username": "johnd",
"bio": "Some example data about John",
"website": "http://john.com",
"profile_picture": "http://john.com/me.jpg",
"full_name": "John Doe",
"counts": {
"media": 13,
"followed_by": 26,
"follows": 49
},
"id": "16"
},
"dashboard": {
"script": {
"tags": ["media"],
"stats": {
"liked": 0,
"lastrun": "never",
"duration": 0
},
"status": {
"code": 0,
"slug": "disabled",
"human": "Disabled",
"message": "Not running."
}
},
"account": {
"plan": "free",
"created": 1419261005373,
"updated": 1419261005373
}
},
"serverInformation": {
"serverName": "Johns API",
"apiVersion": "0.0.1",
"requestDuration": 22,
"currentTime": 1419262805646
},
"requesterInformation": {
"id": "redacted",
"fingerprint": "redacted",
"remoteIP": "redacted",
"receivedParams": {
"action": "getDashboard",
"apiVersion": 1
}
}
}
最佳答案
这是我写的解决方案:
function iterate(obj, stack) {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
iterate(obj[property], stack + '-' + property);
} else {
$group = $('.ajax' + stack + '-' + property);
$.each($group, function(key, element) {
if ($(element).data('attr')) {
$(element).attr($(element).data('attr'), obj[property]);
} else {
$(element).text(obj[property]);
}
});
}
}
}
}
关于javascript - 循环遍历对象并替换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27606014/