gpt4 book ai didi

javascript - 使用 jQuery 动态创建对象

转载 作者:行者123 更新时间:2023-12-03 02:33:57 25 4
gpt4 key购买 nike

我想动态创建对象数组。

该数组将被称为“组”。它将包含未知数量的对象(这些是组名称),这些对象将由元素的 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"
}

}

最佳答案

您可以使用 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>

关于javascript - 使用 jQuery 动态创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48613083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com