2 回答

TA贡献1811条经验 获得超4个赞
这是你想要的?
let divs = document.querySelectorAll('div');
let obj = [];
divs.forEach(element => {
let e = {
id: element.id,
name: element.getAttribute("name"),
class: element.className,
title: element.title,
text: element.getAttribute("text")
};
obj.push(e);
})
console.log(obj)
<div id="ID_a" name="VEC" class="cat" title="scene,-12, 0.5, 0, 1" text="$\omega =9$"> </div>
<div id="ID_b" name="VEC" class="cat" title="scene,-12, 0.5, 0, 3" text="$\alfa = 2$"> </div>
<div id="ID_c" name="VEC" class="cat" title="scene,-12, 0.5, 0, 4" text="$\beta = 30.5$"></div>
<div id="ID_d" name="VEC" class="cat" title="scene,-12, 0.5, 0, 2" text="$\gamma = 90$"> </div>

TA贡献1815条经验 获得超6个赞
假设您将所有 div 作为字符串加载,您可以将每个字符串映射到一个对象。这可以通过按每个属性拆分字符串(通过regex)然后通过reduce将这些字符串转换为对象来完成。
因为某些值包含等号,所以我搜索第一次出现的索引,并在将其作为对象返回之前将字符串拆分为带有切片的键和值。
const divs = [
'<div id="ID_a" name="VEC" class="cat" title ="scene,-12, 0.5, 0, 1" text = "$\omega =9$"> </div>',
'<div id="ID_b" name="VEC" class="cat" title ="scene,-12, 0.5, 0, 3" text = "$\alfa = 2$"> </div>',
'<div id="ID_c" name="VEC" class="cat" title ="scene,-12, 0.5, 0, 4" text = "$\beta = 30.5$"></div>',
'<div id="ID_d" name="VEC" class="cat" title ="scene,-12, 0.5, 0, 2" text = "$\gamma = 90$"> </div>',
];
const Coll = divs.map((div) => {
const parts = div.match(/[\w-]+\s?=\s?"[^"]*"/g);
const objectified = parts.reduce((obj, str) => {
const index = str.indexOf("=");
const key = str.slice(0, index);
const value = str.slice(index + 1, str.length);
obj[key] = value;
return obj;
}, {});
return objectified;
});
console.log("Single value:", Coll[0].id);
console.log(Coll);
.as-console-wrapper { max-height: 100% !important; }
添加回答
举报