我正在遍歷一些資料,這些資料是從一些網站上抓取的。目前我正在刮頭。
這是資料結構的一個例子
const head = {
rel_data: [
{
rel: "rel",
items: [
{
type: "type",
sizes: "sizes",
href: "href"
}
]
}
]
};
每當rel匹配時,我想將資料插入items
$('head link').each(function(index) {
if(head?.rel_data[index]?.rel == rel) {
head?.rel_data[index]?.items.push({
type: (type !== undefined) ? type : null,
sizes: (sizes !== undefined) ? sizes : null,
href: (href !== undefined) ? href : null
});
} else {
head.rel_data.push({
rel: (rel !== undefined) ? rel : null,
items: [
{
type: (type !== undefined) ? type : null,
sizes: (sizes !== undefined) ? sizes : null,
href: (href !== undefined) ? href : null
}
]
});
}
})
像這樣
rel_data: [
{
rel: "icon",
items: [
{
type: "type",
sizes: "sizes",
href: "href"
},
{
type: "type",
sizes: "sizes",
href: "href"
}
]
},
{
rel: "other-rel-type",
items: [...]
}
]
但我得到的是這個。
rel_data: [
{
rel: "icon",
items: [
{
type: "type",
sizes: "sizes",
href: "href"
}
]
},
{
rel: "icon",
items: [
{
type: "type",
sizes: "sizes",
href: "href"
}
]
}
]
如果我寫0, 而不是index, 它適用于第一種型別rel(例如圖示)而不是其他型別?
uj5u.com熱心網友回復:
一個簡單的解決方案是將資料存盤在臨時物件而不是陣列中,并將rel值用作鍵。
然后當你完成使用Object.values(tempObject)來獲得最終的陣列
這個物件看起來像:
const obj = {
"icon": {
rel: "icon",
items: [{
type: "type",
sizes: "sizes",
href: "href"
}
]
},
"other-rel-type": {
rel: "other-rel-type",
items: []
}
}
然后回圈的簡化版本將類似于:
$('head link').each(function(index) {
const rel = this.rel
obj[rel] = obj[rel] || { rel, items:[]}
obj[rel].items.push({type:..., sizes:...})
});
然后最后:
head.rel_data = Object.values(obj)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/387387.html
