我想动态创建一个对象数组。
阵列将被称为' groups'。它将包含未知数量的对象(这些是组名称),它们将由元素的ID
确定。每个对象将包含未知数量的属性(这些是属性组),这些属性将由div
的内部文本确定,它们的值将由另一个div
的内部文本确定。
我知道如何使用.each()
和.attr('ID')
以及.text()
获取每个值。我无法解决如何创建对象数组的问题。
// Example HTML
<div id="england">
<div class="property">health</div>
<div class="count">3</div>
<div class="property">education</div>
<div class="count">1</div>
<div class="property">entertainment</div>
<div class="count">12</div>
</div>
<div id="scotland">
<div class="property">geography</div>
<div class="count">5</div>
<div class="property">history</div>
<div class="count">2</div>
</div>
<div id="wales">
<div class="property">illustration</div>
<div class="count">4</div>
<div class="property">business</div>
<div class="count">6</div>
<div class="property">fashion</div>
<div class="count">3</div>
</div>
// Example JSON output of the 'groups' array
{
"england":{
"health":"3",
"education":"1",
"entertainment":"12"
},
"scotland":{
"geography":"5",
"history":"2"
},
"wales":{
"illustration":"4",
"business":"6",
"fashion":"3"
}
}
答案 0 :(得分:1)
您可以使用reduce()
执行此操作以返回对象,并使用Array.from
将jQuery对象转换为对象数组,以便您可以使用reduce
方法。
// Select direct div children of body, make an array from them and use reduce on it
const data = Array.from($('body > div')).reduce(function(r, e) {
// Add property for each div / object in array where key is id and value will be another object from array of children of current div
r.groups[e.id] = Array.from($(e).children())
.reduce(function(acc, el, i, arr) {
// Here we are looping each element in div and if (i % 2 == 0) that means its property so we will use it for key and the next one will be used for value
if (i % 2 == 0) acc[el.textContent] = arr[i + 1].textContent
// return accumulator
return acc
}, {})
// return accumulator
return r;
// Accumulator of first reduce is object with groups property
}, {groups: {}})
console.log(data)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="england">
<div class="property">health</div>
<div class="count">3</div>
<div class="property">education</div>
<div class="count">1</div>
<div class="property">entertainment</div>
<div class="count">12</div>
</div>
<div id="scotland">
<div class="property">geography</div>
<div class="count">5</div>
<div class="property">history</div>
<div class="count">2</div>
</div>
<div id="wales">
<div class="property">illustration</div>
<div class="count">4</div>
<div class="property">business</div>
<div class="count">6</div>
<div class="property">fashion</div>
<div class="count">3</div>
</div>