問題描述
使用reduce轉換一個js對象 (transform a js object using reduce)
我想寫一個函數來傳輸這個對象
[
{
"id": "656DDXFT565xX",
"name": "Black item",
"categorues": [
"Black",
"White"
],
"price": 5
}
]
變成那樣的東西
[
{
"Black": [
{
"id": "656DDXFT565xX",
"name": "Black item",
"categories": [
"Black",
"White"
],
"price": 5
}
]
},
{
"White": [
{
"id": "656DDXFT565xX",
"name": "Black item",
"categories": [
"Black",
"White"
],
"price": 5
}
]
}
]
我試過用Array.reduce,但我不知道怎麼做渲染這個。
如果有人對此有任何後見之明
參考解法
方法 1:
let before = [
{
"id": "656DDXFT565xX‑BW",
"name": "Black and white item",
"categories": [
"Black",
"White"
],
"price": 5
},
{
"id": "656DDXFT565xX‑K",
"name": "Black item",
"categories": [
"Black"
],
"price": 10
},
{
"id": "656DDXFT565xX‑W",
"name": "White item",
"categories": [
"White"
],
"price": 15
}
]
let after = before.reduce(
(acc, val) => {
val.categories.forEach(cat => {
acc[cat] ||= []
// if this fails, use newer version of node, or use
// if(!acc.cat) acc.cat = []
acc[cat].push(val)
})
return acc
},
{}
)
console.log(after)
</code></pre>
方法 2:
You can iterate over the categorues
of each item using .map
to get the expected result. This a solution using lodash
:
const data = [
{ "id":"656DDXFT565xX", "name":"Colored item", "categorues":["Black","White"], "price":5 },
{ "id":"656DDXFT565x2", "name":"White item", "categorues":["White"], "price":5 },
{ "id":"656DDXFT565x3", "name":"Black item", "categorues":["Black"], "price":5 }
];
const _reduceElem = (elem={}) => {
const { categorues=[] } = elem;
return _.map( categorues, cat => ({ [cat]: [_.cloneDeep(elem)] }) );
}
const res = _.reduce(data, (acc,item) => {
acc = [...acc, ..._reduceElem(item)];
return acc;
}, []);
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512‑WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous"></script>
方法 3:
Since you just want to extract categorues
as a key. You don't need to use reduce
, just using map
to loop the categorues
is fine.
const origin = [
{
"id": "656DDXFT565xX",
"name": "Black item",
"categorues": [
"Black",
"White"
],
"price": 5
}
]
const categorues = origin[0].categorues;
const result = categorues.map(item => {
return {
[item]: origin
}
})
console.log(result)
(by Moaud louhichi、ΔO 'delta zero'、Majed Badawi、bcjohn)
參考文件