[英]How to efficiently construct new object array using unique values from arrays of children inside an array of parent objects
[英]How to construct an array of object to unique array of object
我有一個這樣的數組 object
let data =
[
{
text: 'label'
},
{
text: 'username'
},
{
text: 'category'
},
{
text: 'book'
},
{
text: 'john'
},
{
text: 'education'
},
{
text: 'car'
},
{
text: 'doe'
},
{
text: 'automotive'
},
{
text: 'shoes'
},
{
text: 'cena'
},
{
text: 'fashion'
},
]
和我期望的對象數組
let result =
[
{
label: 'book',
username: 'john',
category: 'education'
},
{
label: 'car',
username: 'doe',
category: 'automotive'
},
{
label: 'shoes',
username: 'cena',
category: 'fashion'
},
]
只是一個簡單for
循環可能是最清楚的。 這里將每個 object 存儲在一個temp
變量中,以避免每次迭代都必須訪問結果數組的末尾,並將size
抽象為一個變量。
let data = [{ text: 'label' }, { text: 'username' }, { text: 'category' }, { text: 'book' }, { text: 'john' }, { text: 'education' }, { text: 'car' }, { text: 'doe' }, { text: 'automotive' }, { text: 'shoes' }, { text: 'cena' }, { text: 'fashion' },]; const size = 3; const result = []; for (let temp, i = size; i < data.length; i++) { if (i % size === 0) { result.push(temp = {}); } temp[data[i % size].text] = data[i].text; } console.log(result)
帶有模%
運算符的switch-case
如何檢查當前密鑰:
const transformData = (data) => { let result = []; let tmpObj = {}; data.forEach((element, idx) => { switch (idx % 3) { case 0: tmpObj["label"] = element.text; break; case 1: tmpObj["username"] = element.text; break; case 2: result.push({...tmpObj, category: element.text }); tmpObj = {}; break; default: break; } }); return result; }; console.log(transformData(getSampleData())); function getSampleData() { return [{ text: 'label' }, { text: 'username' }, { text: 'category' }, { text: 'book' }, { text: 'john' }, { text: 'education' }, { text: 'car' }, { text: 'doe' }, { text: 'automotive' }, { text: 'shoes' }, { text: 'cena' }, { text: 'fashion' }, ]; }
根據你的數據,前3條記錄是屬性名,其他是數據,所以我們可以使用Array.slice()
來獲取屬性名
然后我們可以使用Array.reduce()
來轉換左邊的數據
let keys = data.slice(0,3).map(v => v.text)
let result = data.slice(3).reduce((a,c,i) =>{
let key = keys[i%3]
if(i%keys.length ==0){
let obj = {}
obj[key] = c.text
a.push(obj)
}else{
a.at(-1)[key]=c.text
}
return a
},[])
console.log(result)
let data = [ { text: 'label' }, { text: 'username' }, { text: 'category' }, { text: 'book' }, { text: 'john' }, { text: 'education' }, { text: 'car' }, { text: 'doe' }, { text: 'automotive' }, { text: 'shoes' }, { text: 'cena' }, { text: 'fashion' }, ] let keys = Object.values(data.slice(0,3)).map(v => v.text) let result = data.slice(3).reduce((a,c,i) =>{ let key = keys[i%3] if(i%keys.length ==0){ let obj = {} obj[key] = c.text a.push(obj) }else{ a.at(-1)[key]=c.text } return a },[]) console.log(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.