使用reduce轉換一個js對象 (transform a js object using reduce)


問題描述

使用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 Badawibcjohn)

參考文件

  1. transform a js object using reduce (CC BY‑SA 2.5/3.0/4.0)

#reduce #javascript #arrays






相關問題

Lapack 的行縮減 (Lapack's row reduction)

泡菜cython類 (pickle cython class)

將列表列表減少為字典,以子列表大小為鍵,出現次數為值 (Reduce list of list to dictionary with sublist size as keys and number of occurances as value)

使用 map/reduce 在列表中添加一對數字的差異 (Adding difference of pair of numbers in list using map/reduce)

Python 2.7:使用 reduce 驗證元素是否在列表中 (Python 2.7: Using reduce to verify that elements are in a list)

使用 map/reduce 計算總數 (Using map/reduce to calculate totals)

Swift reduce - 為什麼 value 是可選的? (Swift reduce - why is value optional?)

獲取具有對像一鍵值的數組的平均值 - Javascript (Get the avarage value of array with objects one key value - Javascript)

如何將數據數組轉換為在顫振/飛鏢中展開或折疊的小部件列表? (How to convert an array of data to a list of widgets with expand or fold in flutter/dart?)

樹的字符串路徑 (JavaScript) (String-path to Tree (JavaScript))

如何重命名對像數組中對象的所有鍵? (How does one rename all of an object's keys within an array of objects?)

使用reduce轉換一個js對象 (transform a js object using reduce)







留言討論