我有數組terms
:
[
{
"label": "programming",
"id": 6,
"taxonomy": "category"
},
{
"label": "design",
"id": 4,
"taxonomy": "post_tag"
},
{
"label": "css",
"id": 3,
"taxonomy": "post_tag"
},
{
"label": "other",
"id": 8,
"taxonomy": "category"
}
]
我正在嘗試newArray
從數組創建以下數組terms
:
[
{
"taxonomy": "category",
"ids": [6, 8]
},
{
"taxonomy": "post_tag",
"ids": [4, 3]
},
]
我必須id
從terms
數組中的每個對像中取出並將它們添加到數組中相應的分類法中newArray
。
我正在嘗試以下操作:
const taxonomyArray = [];
const newArray = [];
// Loop through original term array and get the taxonomies
terms.forEach( el => {
taxonomyArray.push( el['taxonomy'] )
});
// Remove duplicate taxonomy values from array taxonomyArray
const uniqueTaxonomyArray = [ ...new Set(taxonomyArray) ];
// Create the new array
uniqueTaxonomyArray.forEach( el => {
const groupedArray = terms
.filter( ( { taxonomy } ) => taxonomy === el )
.map( ( { value, taxonomy } ) => ( {
taxonomy: el,
ids: value
} ) );
newArray.push( groupedArray );
});
它給了我:
[
[
{
"taxonomy": "category",
"ids": 6
},
{
"taxonomy": "category",
"ids": 8
}
],
[
{
"taxonomy": "post_tag",
"ids": 4
},
{
"taxonomy": "post_tag",
"ids": 3
}
]
]
有沒有更好的方法來實現這一目標?
Array.reduce
和 Map
const terms = [ { "label": "programming", "id": 6, "taxonomy": "category" }, { "label": "design", "id": 4, "taxonomy": "post_tag" }, { "label": "css", "id": 3, "taxonomy": "post_tag" }, { "label": "other", "id": 8, "taxonomy": "category" }];
const map = terms.reduce((acc, {id, taxonomy}) => {
if (acc.has(taxonomy)) {
acc.get(taxonomy).ids.push(id);
} else {
acc.set(taxonomy, {taxonomy: taxonomy, ids: [id]});
}
return acc;
}, new Map());
const result = [...map.values()];
console.log(result);
reducer 逐個元素遍歷數組,在每一步將當前數組值添加到上一步的結果(此結果是所有先前步驟的運行總和)——直到沒有更多元素要添加。
// Arrow function
reduce((previousValue, currentValue) => { ... } )
reduce((previousValue, currentValue, currentIndex) => { ... } )
reduce((previousValue, currentValue, currentIndex, array) => { ... } )
reduce((previousValue, currentValue, currentIndex, array) => { ... }, initialValue)
// Callback function
reduce(callbackFn)
reduce(callbackFn, initialValue)
// Inline callback function
reduce(function(previousValue, currentValue) { ... })
reduce(function(previousValue, currentValue, currentIndex) { ... })
reduce(function(previousValue, currentValue, currentIndex, array) { ... })
reduce(function(previousValue, currentValue, currentIndex, array) { ... }, initialValue)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句