gpt4 book ai didi

javascript - 遍历列表并插入对象数组

转载 作者:行者123 更新时间:2023-11-30 08:20:49 25 4
gpt4 key购买 nike

我有一个这样的列表:

<li class='category parent-category' data-categoryId='1' data-parentCategoryId='' data-parentOrder='1'>
<a href='/category/edit/1'>Business Basics</a>
</li>

<li class='category parent-category' data-categoryId='10' data-parentCategoryId='1' data-parentOrder='2'>
<a href='/category/edit/10'>General/Legal</a>
</li>

<li class='category parent-category' data-categoryId='15' data-parentCategoryId='2' data-parentOrder='3'>
<a href='/category/edit/15'>Home, Help &amp; Links</a>
</li>

我想遍历每个类为“category”的元素,获取数据属性,然后将它们插入到一个数组中。

var categoryData = Object.create(null);
var myArray = [];

$('.category').each(function() {
categoryData.categoryId = category.attr('data-categoryId');
categoryData.parentCategoryId = category.attr('data-parentCategoryId');
categoryData.childOrder = category.attr('data-child-order');
categoryData.parentOrder = category.attr('data-parent-order');

myArray.push(categoryData);
});

但目前它只从第一个元素中获取数据,然后多次将其插入到数组中。

[ 
0 => [ categoryId => 1, parentCategoryId => , childOrder => , parentOrder => 1 ],
1 => [ categoryId => 1, parentCategoryId => , childOrder => , parentOrder => 1 ],
2 => [ categoryId => 1, parentCategoryId => , childOrder => , parentOrder => 1 ]
]

我想要的是:

[ 
0 => [ categoryId => 1, parentCategoryId => , childOrder => , parentOrder => 1 ],
1 => [ categoryId => 10, parentCategoryId => 1, childOrder => , parentOrder => 2 ],
2 => [ categoryId => 15, parentCategoryId => 2, childOrder => , parentOrder => 3 ]
]

最佳答案

还需要将 ref 更改为类别

var myArray = [];

$('.category').each(function() {
let categoryData = Object.create(null);
categoryData.categoryId = $(this).attr('data-categoryId');
categoryData.parentCategoryId = $(this).attr('data-parentCategoryId');
categoryData.childOrder = $(this).attr('data-child-order');
categoryData.parentOrder = $(this).attr('data-parent-order');

myArray.push(categoryData);
});

console.log(myArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li class='category parent-category' data-categoryId='1' data-parentCategoryId='' data-parentOrder='1'>
<a href='/category/edit/1'>Business Basics</a>
</li>

<li class='category parent-category' data-categoryId='10' data-parentCategoryId='1' data-parentOrder='2'>
<a href='/category/edit/10'>General/Legal</a>
</li>

<li class='category parent-category' data-categoryId='15' data-parentCategoryId='2' data-parentOrder='3'>
<a href='/category/edit/15'>Home, Help &amp; Links</a>
</li>

关于javascript - 遍历列表并插入对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53950178/

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