我有 2 個陣列標簽和型別名:
const tags = [
{
title: 'Warrior',
data: {
type: 'audience'
}
},
{
title: 'Juggler',
data: {
type: 'section'
}
},
{
title: 'Journey',
data: {
type: 'audience'
}
},
{
title: 'Travel',
data: {
type: 'nonexistingtag'
}
}
];
const typenames = [
{ audience: 'au' },
{ section: 'se' },
{ sponsor: 'sp' },
{ contextual: 'co' }
]
預期的輸出是創建一個字串,該字串由在 array1 和 array2 型別之間匹配的鍵分組,每個鍵由管道“|”分隔 符號和每個組由“&”彼此分隔,因此對于上述示例,最終預期的輸出字串將是:
au=Warrior|au=Journey&se=Juggler
這是我到目前為止所嘗試的,
let arr = [];
tags.forEach(element => {
typenames.forEach(el => {
if (Object.keys(el)[0] === element.data.type) // finding matching keys and pushing to an arr
arr.push({ title: Object.values(el)[0], desc: element.title });
})
});
對鍵進行排序,以便它們易于分組:
arr.sort((a, b) => {
let keya = a.title;
let keyb = b.title;
if (keya > keyb) {
return 1;
} else if (keya < keyb) {
return -1;
} else {
// the characters are equal.
return 0;
}
});
連接字串:
let str = '';
arr.forEach(({ title, desc }, i, arr2) => {
if (title === arr2[i 1]?.title) { // Check that the next item in array has the same title
str = str.concat(`${title}=${desc}|`)
return;
}
str = str.concat(`&${title}=${desc}`)
});
console.log('str', str);
輸出 :
au=Warrior|&au=Journey&se=Juggler
問題 :
- 由于我正在檢查陣列中的下一項以查看標題是否匹配,因此有一個額外的不需要的“&”
- 有沒有更簡單的方法來完成同樣的事情?(使用速記、過濾器等?)
uj5u.com熱心網友回復:
考慮到這個問題,您最終希望遍歷所有型別名并查看標簽中匹配的值 - 因此您應該首先將標簽陣列重組為更容易搜索的東西,而不是嘗試通過整個有點復雜每次的結構。也許是按型別索引的物件,例如:
{
audience: ['Warrior', 'Journey'],
section: ['Juggler'],
nonexistingtag: ['nonexistingtag']
}
然后在查看型別名稱時,您需要做的就是查找物件上的鏈接屬性,然后加入兩次:
- 一次加入頭銜:
['Warrior', 'Journey']到au=Warrior|au=Journey - 一次將所有型別名稱中的連接標題加入到單個字串中
使用可以連接的分組資料結構(如陣列)要容易得多,而不是根據陣列中的下一項是否具有特定屬性來添加分隔符。
const tags=[{title:"Warrior",data:{type:"audience"}},{title:"Juggler",data:{type:"section"}},{title:"Journey",data:{type:"audience"}},{title:"Travel",data:{type:"nonexistingtag"}}],typenames=[{audience:"au"},{section:"se"},{sponsor:"sp"},{contextual:"co"}];
const titlesByType = {};
for (const { title, data: { type } } of tags) {
titlesByType[type] ??= [];
titlesByType[type].push(title);
}
const combinedStrs = [];
for (const typeObj of typenames) {
const [[key, abbrev]] = Object.entries(typeObj);
if (titlesByType[key]) {
combinedStrs.push(titlesByType[key].map(str => `${abbrev}=${str}`).join('|'));
}
}
const output = combinedStrs.join('&');
console.log(output);
uj5u.com熱心網友回復:
使用陣列來處理標記化
這是在組裝字串時智能地“粘合”正確的標準技巧。
- 首先創建一個專案陣列
- 用于
Array.prototype.join生成最終字串
我在想這樣的事情:
let items = arr.reduce((output, { title, desc }, i, fullArray) => {
if (title === fullArray[i 1]?.title) {
output.push(`${title}=${desc}|`)
}
return output
}, [])
let str = items.join('&')
uj5u.com熱心網友回復:
你可以試試這個簡單易讀的方法:
const availableTags = [
{
title: 'Warrior',
data: {
type: 'audience'
}
},
{
title: 'Juggler',
data: {
type: 'section'
}
},
{
title: 'Journey',
data: {
type: 'audience'
}
},
{
title: 'Travel',
data: {
type: 'nonexistingtag'
}
}
];
const availableTypenames = [
{
audience: 'au'
},
{
section: 'se'
},
{
sponsor: 'sp'
},
{
contextual: 'co'
}
];
const getResultString = (tags, typenames) => {
let result = '';
for (const typename of typenames) {
const type = Object.keys(typename)[0];
let needSeparate = false;
for (const tag of tags) {
if (type === tag.data.type) {
result =`${needSeparate ? '|' : '&'}${typename[type]}=${tag.title}`;
needSeparate = true;
}
}
}
return result.slice(1);
}
console.log(getResultString(availableTags, availableTypenames))
uj5u.com熱心網友回復:
我會這樣做...
const tags =
[ { title: 'Warrior', data: { type: 'audience' } }
, { title: 'Juggler', data: { type: 'section' } }
, { title: 'Journey', data: { type: 'audience' } }
, { title: 'Travel', data: { type: 'nonexistingtag' } }
]
const typenames =
[ { audience : 'au' }
, { section : 'se' }
, { sponsor : 'sp' }
, { contextual : 'co' }
]
// build jso_K = { audience:{ref:'au',titles:[]},section:{ref:'se',titles:[]},sponsor: ...}
let jso_K = typenames.reduce((r,e)=>
{
let [k,v] = Object.entries(e)[0]
r[k] = {ref:v, titles:[] }
return r
},{})
// complete jso_K on titles --> { audience:{ref:'au',titles:['Warrior','Journey' ] }, section:...
tags.forEach(({title,data})=>
{
if (jso_K.hasOwnProperty(data.type)) jso_K[data.type].titles.push(title)
})
// Build result
let txt = Object.keys(jso_K).reduce((t,k) =>
{
if (jso_K[k].titles.length > 0) t.push( jso_K[k].titles.map(t=>`${jso_K[k].ref}=${t}`).join('|'))
return t
},[]).join('&')
console.log( txt )
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/441070.html
標籤:javascript 数组 排序 分组
上一篇:如何確定哪個點離另一個點最近?
