我在页面上有动态div,该页面具有一堆值分配的类。例如:
<div class='class1'><span class='spn1'>test</span></div>
<div class='class2'><span class='spn2'>test another</span></div>
<div class='class2'><span class='spn3'>test1</span></div>
<div class='class3'><span class='spn4'>test123</span></div>
<div class='class1'><span class='spn221'>test</span></div>
该类可以附加任何随机数。
现在,在我的JavaScript中,我试图基于div的类和所需的结构构建一个动态JSON对象:
{
class1: {
spn1: 'test',
spn221: 'test'
},
class2: {
spn2: 'test another',
spn3: 'test123'
},
class3: {
spn4: 'test223'
}
}
我能够以平面数组结构实现此功能,但我希望它采用JSON格式,因为我将在其他函数中基于div的类执行ajax调用。我得到的平面数组是(我不想)
[{class:class1,span:spn1,text:test},{class:class1,span:spn221,text:test},...]
链接到小提琴:https://jsfiddle.net/8v0uove3/
最佳答案
这是一种普通的JS方式:
// pick up the elements
var divs = document.querySelectorAll('div[class^="class"]');
// use reduce with an initial object
var obj = [].slice.call(divs).reduce(function (p, c) {
var child = c.firstChild;
var key = c.getAttribute('class');
// if the class key doesn't exist in the initial object add it
if (!p[key]) p[key] = {};
// add the new span properties to the object
p[key][child.getAttribute('class')] = child.textContent;
return p;
}, {});
输出量
{
"class1": {
"spn1": "test",
"spn221": "test"
},
"class2": {
"spn2": "test another",
"spn3": "test1"
},
"class3": {
"spn4": "test123"
}
}
DEMO
关于javascript - 动态嵌套JSON对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34000162/