マッピングおよびグループ化関数を備えたlodashを使用して、JSON記事をグループ化する方法を理解しようとしています。私は一般的にlodashとjavascriptにかなり慣れていませんが、近づいていますが、フォーマットの最後のビットを理解できません!
私が試したこと
const data = [{
"pcc": "1ADA",
"markets": {
"origin": "ORG",
"destination": "DES"
}
}, {
"pcc": "1ADA",
"markets": {
"origin": "ORD",
"destination": "DES"
}
},{
"pcc": "1ADA",
"markets": {
"origin": "ORG",
"destination": "DES"
}
}, {
"pcc": "1AZA",
"markets": {
"origin": "ORG",
"destination": "DES"
}
}, {
"pcc": "1AXA",
"markets": {
"origin": "ORG",
"destination": "DES"
}
}]
excelDef = _(data)
.groupBy("pcc")
.map((group, pcc) =>({
pcc,
markets: group.map(({origin, markets: destination}) => ({
origin,
destination
}))
}))
.value();
私が得ている出力
[{
"pcc": "1ADA",
"markets": [{
"destination": {
"origin": "ORG",
"destination": "DES"
}
}, {
"destination": {
"origin": "ORD",
"destination": "DES"
}
}, {
"destination": {
"origin": "ORG",
"destination": "DES"
}
}]
}, {
"pcc": "1AZA",
"markets": [{
"destination": {
"origin": "ORG",
"destination": "DES"
}
}]
}, {
"pcc": "1AXA",
"markets": [{
"destination": {
"origin": "ORG",
"destination": "DES"
}
}]
}]
必要な出力
[{
"pcc": "1ADA",
"markets": [{
"origin": "ORG",
"destination": "DES"
}, {
"origin": "ORD",
"destination": "DES"
}, {
"origin": "ORG",
"destination": "DES"
}]
}, {
"pcc": "1AZA",
"markets": [{
"origin": "ORG",
"destination": "DES"
}]
}, {
"pcc": "1AXA",
"markets": [{
"origin": "ORG",
"destination": "DES"
}]
}]
希望する出力に近づいているように感じますが、マッピングおよびグループ化関数の構文は、プログラミングを始めている人として常に私を失望させます。どんな助けでもいただければ幸いです!
別のアプローチでは、なしでlodash
、次を使用できますreduce
:
const data=[{"pcc":"1ADA","markets":{"origin":"ORG","destination":"DES"}},{"pcc":"1ADA","markets":{"origin":"ORD","destination":"DES"}},{"pcc":"1ADA","markets":{"origin":"ORG","destination":"DES"}},{"pcc":"1AZA","markets":{"origin":"ORG","destination":"DES"}},{"pcc":"1AXA","markets":{"origin":"ORG","destination":"DES"}}]
const resp = data.reduce((acc, ele) => {
const ant = acc.find(x => x.pcc === ele.pcc);
if(!ant) return acc.concat({pcc: ele.pcc, markets: [ele.markets]});
ant.markets.push(ele.markets);
return acc;
}, []);
console.log(resp);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加