LoginSignup
0

More than 5 years have passed since last update.

[Node.js][lodash] オブジェクトの配列をユニークにする(マージする)

Last updated at Posted at 2018-11-06

オブジェクトの配列をユニークする(マージする)方法です。結果は配列のオブジェクトになります。
null は値としてカウントせず、 null 以外の値が重複した場合だけユニークにしています。

const lodash = require('lodash');

let array = [
  {
    "job": "会社員",
    "name": "荒木 幸也"
  },
  {
    "job": "自営業",
    "name": "森岡 七美"
  },
  {
    "job": "会社員",
    "name": null
  }
];

let result = array.reduce(function(res, obj){
  Object.keys(obj).forEach(function(k){
    res[k] = res[k] || [];
    res[k] = res[k].concat(obj[k]);
    res[k] = lodash(res[k]).uniq().compact().value();
 });
 return res;
},{});
/*
 => {
   "job": [
     "会社員",
     "自営業"
   ],
   "name": [
     "荒木 幸也",
     "森岡 七美"
   ]
}
 */

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0