te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>lodash - merge object & sum a single property javascript - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

lodash - merge object & sum a single property javascript - Stack Overflow

programmeradmin4浏览0评论

i have an array like this

[
  {
    item_guid: "57e7a1cd6a3f3669dc03db58"
    quantity:3
  },
  {
    item_guid: "57e77b06e0566d496b51fed5"
    quantity:3
  },
  {
    item_guid: "57e7a1cd6a3f3669dc03db58"
    quantity:3
   },
  {
    item_guid: "57e77b06e0566d496b51fed5"
    quantity:3
  }
]

What i want from this to merge similar item_guid into one object and quantity get summed up like this

[
  {
    item_guid: "57e7a1cd6a3f3669dc03db58"
    quantity:6
   },
  {
    item_guid: "57e77b06e0566d496b51fed5"
    quantity:6
  }
]

I know this can be achieved some loop, instead I'm looking for solutions that uses lodash or EcmaScript2015 code to make our life easier

i have an array like this

[
  {
    item_guid: "57e7a1cd6a3f3669dc03db58"
    quantity:3
  },
  {
    item_guid: "57e77b06e0566d496b51fed5"
    quantity:3
  },
  {
    item_guid: "57e7a1cd6a3f3669dc03db58"
    quantity:3
   },
  {
    item_guid: "57e77b06e0566d496b51fed5"
    quantity:3
  }
]

What i want from this to merge similar item_guid into one object and quantity get summed up like this

[
  {
    item_guid: "57e7a1cd6a3f3669dc03db58"
    quantity:6
   },
  {
    item_guid: "57e77b06e0566d496b51fed5"
    quantity:6
  }
]

I know this can be achieved some loop, instead I'm looking for solutions that uses lodash or EcmaScript2015 code to make our life easier

Share Improve this question edited Oct 26, 2016 at 12:42 Faysal Ahmed asked Oct 26, 2016 at 12:33 Faysal AhmedFaysal Ahmed 1,54213 silver badges28 bronze badges 2
  • my suggestion is use Linq.js rather than writing custom method for achieve this linqjs.codeplex. – Shobhit Walia Commented Oct 26, 2016 at 12:35
  • Any ideas on how to do this with lodash? – sudocity Commented Oct 12, 2022 at 14:14
Add a ment  | 

4 Answers 4

Reset to default 5

A simple approach:

Loop over data and create an object where key will be unique id and its value will be quantity. Then loop back over object's keys and create objects.

var data = [{ item_guid: "57e7a1cd6a3f3669dc03db58", quantity: 3 }, { item_guid: "57e77b06e0566d496b51fed5", quantity: 3 }, { item_guid: "57e7a1cd6a3f3669dc03db58", quantity: 3 }, { item_guid: "57e77b06e0566d496b51fed5", quantity: 3 }]

var r = {};
data.forEach(function(o){
  r[o.item_guid] = (r[o.item_guid] || 0) + o.quantity;
})

var result = Object.keys(r).map(function(k){
  return { item_guid: k, quantity: r[k] }
});
console.log(result)

A solution in plain Javascript with a hash table for item_guid.

var data = [{ item_guid: "57e7a1cd6a3f3669dc03db58", quantity: 3 }, { item_guid: "57e77b06e0566d496b51fed5", quantity: 3 }, { item_guid: "57e7a1cd6a3f3669dc03db58", quantity: 3 }, { item_guid: "57e77b06e0566d496b51fed5", quantity: 3 }],
    grouped = data.reduce(function (hash) {
        return function (r, a) {
            (hash[a.item_guid] = hash[a.item_guid] || r[r.push({ item_guid: a.item_guid, quantity: 0 }) - 1]).quantity += a.quantity;
            return r;
        };
    }(Object.create(null)), []);

console.log(grouped);

ES6

var data = [{ item_guid: "57e7a1cd6a3f3669dc03db58", quantity: 3 }, { item_guid: "57e77b06e0566d496b51fed5", quantity: 3 }, { item_guid: "57e7a1cd6a3f3669dc03db58", quantity: 3 }, { item_guid: "57e77b06e0566d496b51fed5", quantity: 3 }],
    grouped = data.reduce((map => (r, a) => {
        map.set(a.item_guid, map.get(a.item_guid) || r[r.push({ item_guid: a.item_guid, quantity: 0 }) - 1]);
        map.get(a.item_guid).quantity += a.quantity;
        return r;
    })(new Map), []);

console.log(grouped);

You can

  • group your objects by item_guid
  • sum the objects in the resulting groups
  • transform these groups in the format you want

Something like this:

var result = _.chain(data)
    .groupBy('item_guid')
    .map(function(objects, guid) {
        return {
            item_guid: guid, 
            quantity: _.sumBy(objects, 'quantity')
        };
    })
    .value();

And a demo

var data = [
  {
    item_guid: "57e7a1cd6a3f3669dc03db58",
    quantity:3
  },
  {
    item_guid: "57e77b06e0566d496b51fed5",
    quantity:3
  },
  {
    item_guid: "57e7a1cd6a3f3669dc03db58",
    quantity:3
   },
  {
    item_guid: "57e77b06e0566d496b51fed5",
    quantity:3
  }
];


var result = _.chain(data)
    .groupBy('item_guid')
    .map(function(objects, guid) {
        return {
            item_guid: guid, 
            quantity: _.sumBy(objects, 'quantity')
        };
    })
    .value();
  
  console.log(result);
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

var groupedItems = [];

var totalItems = [{item_guid: "57e7a1cd6a3f3669dc03db58", quantity:3},{item_guid: "57e77b06e0566d496b51fed5",quantity:3}, { item_guid: "57e7a1cd6a3f3669dc03db58", quantity:3 }, { item_guid: "57e77b06e0566d496b51fed5", quantity:3}];

totalItems.forEach((e) => {
  if (groupedItems.findIndex(x => x.item_guid === e.item_guid) < 0) {
    let totalQuantity = totalItems
                       .filter(x => x.item_guid === e.item_guid)
                       .map(x => x.quantity)
                       .reduce(function(a, b) { return a + b;});

    groupedItems.push({item_guid: e.item_guid, quantity: totalQuantity})
  }
})

console.log(groupedItems);
发布评论

评论列表(0)

  1. 暂无评论