我有陣列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
}
]
]
有沒有更好的方法來實作這一目標?
uj5u.com熱心網友回復:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/362947.html
標籤:javascript 循环
