[英]What is the best way to achieve the following result?
我有以下數據:
const data = [
{
id: 1,
metadata: {
attributes: [
{
type: 'background',
value: 'red',
},
{
type: 'background',
value: 'blue',
},
{
type: 'size',
value: 'small',
},
],
},
},
{
id: 2,
metadata: {
attributes: [
{
type: 'background',
value: 'red',
},
{
type: 'background',
value: 'blue',
},
],
},
},
{
id: 3,
metadata: {
attributes: [
{
type: 'background',
value: 'red',
},
{
type: 'background',
value: 'green',
},
{
type: 'size',
value: 'small',
},
],
},
},
];
對於屬性數組中的每個對象,我必須基於 type 屬性創建一個新對象。 type 屬性將是這個新對象中的鍵,值將是嵌套在其中的另一個屬性。 嵌套屬性的值將是一個包含所有相應 id 的數組。 所以,我必須實現這樣的最終結果:
const desiredResult = {
background: {
red: [1, 2, 3], //these are ids
blue: [1, 2],
green: [3],
},
size: {
small: [1, 3],
},
};
您可以在 javascript 中嘗試for each
或for ... of
。 初學者的干凈代碼如下:
function process (data) {
let result = {};
for (let datum of data) {
for (let attribute of datum.metadata.attributes) {
result[attribute.type] = result[attribute.type] || {};
result[attribute.type][attribute.value] = result[attribute.type][attribute.value] || [];
result[attribute.type][attribute.value].push(datum.id);
}
}
return result;
}
//
const desiredResult = process(data);
另一種方法與此處的其他方法非常相似,但使用不可變數據,即使對於累加器也是如此:
const extract = (xs) => xs .reduce ((a, {id, metadata: {attributes = []} = {}}) => attributes .reduce ((a, {type: t, value: v}) => ({...a, [t]: {... (a [t] || {}), [v]: [...((a [t] || {}) [v] || []), id]}}), a), {}) const data = [{id: 1, metadata: {attributes: [{type: "background", value: "red"}, {type: "background", value: "blue"}, {type: "size", value: "small"}]}}, {id: 2, metadata: {attributes: [{type: "background", value: "red"}, {type: "background", value: "blue"}]}}, {id: 3, metadata: {attributes: [{type: "background", value: "red"}, {type: "background", value: "green"}, {type: "size", value: "small"}]}}] console .log (extract (data))
.as-console-wrapper {max-height: 100% !important; top: 0}
這適用於許多大小的數據,但如果數據非常大,它可能會遇到性能問題。 如果你這樣做了,那么你可能不得不選擇一個可變的累加器。 但是我不會擔心它,除非這個函數表明它本身是你應用程序的一個瓶頸。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.