我试图弄清楚如何使用具有映射和分组功能的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"
}]
}]
我感觉自己已经接近所需的输出,但是映射和分组功能的语法总是让我不满意作为开始编程的人。任何帮助将不胜感激!
答案 0 :(得分:0)
以另一种方式,如果没有protected static function rawQuery ($query, array $params = null) {
if ($params === null) {
$params = [];
}
$stmt = static::getPdo()->prepare($query);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute($params);
$results = $stmt->fetchAll();
return $results;
}
,则可以使用lodash
:
reduce