2017-12-08 13 views
0

Map, Filter, Reduce와 같은 고차 함수를 사용하고 싶습니다.
내 문제는 배열 된 배열이있어서 원하는 결과를 얻으려면 루프 연산을 수행해야한다는 것입니다. 배열은 하나의 _idtotalCount 인 배열이며, 길이는 최소 0에서 3이 될 것입니다.
totalCount 각 반복은 두 개의 필드로 구성되며 하나는 orderstatus이고 다른 하나는 total입니다. orderstatus는 "Merchant"또는 "driver"또는 "user"입니다. 반복 된 총계를 가져와 MerchantCount과 같은 배열에 저장하고 싶습니다.두 개의 루프 대신 고차 함수 사용

for (let i = 0; i < recentUserCount.length; i++) { 
    for (let j = 0; j < recentUserCount[i].totalcount.length; j++) { 
    if (recentUserCount[i].totalcount[j].usertype == "DRIVER") { 
     recentUserCount[i].DRIVERCount = recentUserCount[i].totalcount[j].total; 
    } else if (recentUserCount[i].totalcount[j].usertype == "USER") { 
     recentUserCount[i].USERCount = recentUserCount[i].totalcount[j].total; 
    } else if (recentUserCount[i].totalcount[j].usertype == "MERCHANT") { 
     recentUserCount[i].MERCHANTCount = recentUserCount[i].totalcount[j].total; 
    } 
    } 
} 

이 결과는 대략 아래와 같이 될 것입니다 :

0 : {_id: "2017-12-08", totalcount: Array(1), MERCHANTCount: 3, $$hashKey: "object:316"} 
    1 : {_id: "2017-12-07", totalcount: Array(1), MERCHANTCount: 3, $$hashKey: "object:317"} 
    2 : {_id: "2017-12-06", totalcount: Array(1), DRIVERCount: 1, $$hashKey: "object:318"} 
    3 : {_id: "2017-12-04", totalcount: Array(3), DRIVERCount: 1, MERCHANTCount: 2, USERCount: 1, …} 

가 나는 것으로 같은 작업을 할

var arr = [{ 
    _id: "2017-12-08", 
    totalcount: [{ 
    orderstatus: "MERCHANT", 
    total: 1 
    }] 
}, 
{ 
    _id: "2017-12-02", 
    totalcount: [{ 
    orderstatus: "USER", 
    total: 2 
    }] 
}, 
{ 
    _id: "2017-12-06", 
    totalcount: [{ 
    orderstatus: "DRIVER", 
    total: 1 
    }] 
}, 
{ 
    _id: "2017-12-07", 
    totalcount: [{ 
    orderstatus: "MERCHANT", 
    total: 3 
    }] 
}, 
{ 
    _id: "2017-12-04", 
    totalcount: [{ 
     orderstatus: "DRIVER", 
     total: 1 
    }, 
    { 
     orderstatus: "MERCHANT", 
     total: 2 
    }, 
    { 
     orderstatus: "USER", 
     total: 1 
    } 
    ] 
} 
] 

루프가 수행하고 :

내 코드입니다 지도/필터 또는 축소 방법을 사용하여 수행됩니다.

+0

정확히'map' /'reduce'를 사용하고 싶은 이유는 어떻게하면 코드가 개선 될 것이라고 생각합니까? – Bergi

+1

@Bergi이 코드로 내 코드를 향상시킬 것인지 또는 고위 함수를 시도 할 것인지 알 수 없습니다. – Kannan

+0

코드에 부작용이 있습니다 (기존 객체에 필드 추가).). 'for ... of' 루프를 사용하고 NinaScholz의 대답처럼'if' 캐스케이드 대신 동적 속성 이름을 사용하여 간단하게 만들 수 있습니다. – Bergi

답변

4

, FUL L 기능성 니펫

var arr = [{_id:"2017-12-08",totalcount:[{orderstatus:"MERCHANT",total:1}]},{_id:"2017-12-02",totalcount:[{orderstatus:"USER",total:2}]},{_id:"2017-12-06",totalcount:[{orderstatus:"DRIVER",total:1}]},{_id:"2017-12-07",totalcount:[{orderstatus:"MERCHANT",total:3}]},{_id:"2017-12-04",totalcount:[{orderstatus:"DRIVER",total:1},{orderstatus:"MERCHANT",total:2},{orderstatus:"USER",total:1}]}]; 
 

 
    const result = arr 
 
     .map(({_id, totalcount}) => ({ 
 
     totalcount, 
 
     _id, 
 
     ...totalcount.reduce((acc, {orderstatus, total}) => 
 
      ({...acc, [`${orderstatus}count`]: total}), {}) 
 
     })) 
 

 
console.log(result)

https://jsbin.com/kiwalozuxa/edit?html,js,console,output

EDIT : The spread operator (...) (배열 또는 값) 키/오브제의 값을 전파하기 위해 사용된다.

{ 
    a: "a", 
    b: "b", 
    { 
    x: "x", 
    y: "y" 
    } 
} 

내가 부모에 내 "아이"개체를 병합 확산 연산자를 사용 :이 형태의 오브제가 자바 스크립트에서 기술적으로 유효하지 이래로

{ 
    x: "x", 
    y: "y" 
} 

: totcalcount.reduce 여기 객체를 반환 objet 및 농산물 :

{ 
    a: "a", 
    b: "b", 
    x: "x", 
    y: "y" 
} 

나는 감속기에서 동일한 기술을 사용합니다.

+0

이것은 완벽하게 작동하지만 나는 당신의 코드를 이해하지 못했습니다. 그게 ... totalcount의 infront? 이것에 대해 설명해 주시겠습니까? 감사합니다. – Kannan

+0

예, 가능한 빨리 수정합니다. – Epitouille

0

중첩 된 두 개의 forEach 루프로 축소하고 orderstatus을 새 속성의 일부로 사용할 수 있습니다.

var totalReference = { MERCHANT: 'MERCHANTCount', USER: 'USERCount', DRIVER: 'DRIVERCount' }, 
 
    array = [{ _id: "2017-12-08", totalcount: [{ orderstatus: "MERCHANT", total: 1 }] }, { _id: "2017-12-02", totalcount: [{ orderstatus: "USER", total: 2 }] }, { _id: "2017-12-06", totalcount: [{ orderstatus: "DRIVER", total: 1 }] }, { _id: "2017-12-07", totalcount: [{ orderstatus: "MERCHANT", total: 3 }] }, { _id: "2017-12-04", totalcount: [{ orderstatus: "DRIVER", total: 1 }, { orderstatus: "MERCHANT", total: 2 }, { orderstatus: "USER", total: 1 }] }]; 
 

 
array.forEach(function (o) { 
 
    o.totalcount.forEach(function (p) { 
 
     if (totalReference[p.orderstatus]) { 
 
      o[totalReference[p.orderstatus]] = p.total; 
 
     } 
 
    }); 
 
}); 
 

 
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

1

나는 줄이고 할당하는 것 그것을

let res = arr.reduce((a, b) => { 
    let totals = b.totalcount.reduce((x, y) => { 
     x[y.orderstatus + 'Count'] = (x[y.orderstatus + 'Count'] || 0) + y.total; 
     return x; 
    }, {}); 
    return a.concat(Object.assign(b, totals)); 
}, []); 

var arr = [{_id:"2017-12-08",totalcount:[{orderstatus:"MERCHANT",total:1}]},{_id:"2017-12-02",totalcount:[{orderstatus:"USER",total:2}]},{_id:"2017-12-06",totalcount:[{orderstatus:"DRIVER",total:1}]},{_id:"2017-12-07",totalcount:[{orderstatus:"MERCHANT",total:3}]},{_id:"2017-12-04",totalcount:[{orderstatus:"DRIVER",total:1},{orderstatus:"MERCHANT",total:2},{orderstatus:"USER",total:1}]}]; 
 

 
let res = arr.reduce((a, b) => { 
 
    let totals = b.totalcount.reduce((x, y) => { 
 
     x[y.orderstatus + 'Count'] = (x[y.orderstatus + 'Count'] || 0) + y.total; 
 
     return x; 
 
    }, {}); 
 
    return a.concat(Object.assign(b, totals)); 
 
}, []); 
 

 
console.log(res);
ES6 구문 및지도/감소와 함께 꽤 쉽게