4

У меня имеется массив с разными данными , который выглядит примерно так:

[ {
   "_id": "556c978be20c7cd0087c6f10",
   "username": "ivan",
   "music": [
     "Metallica"
   ]
  },
  {
   "_id": "556c978be20c7cd0087c6f10",
   "username": "ivan",
   "interests": [
     "Music",
     "Djent"
   ]
  }, 
  {
   "_id": "556c978be20c7cd0087c6f13",
   "username": "alina",
   "interests": [
     "Music",
     "Literature"
   ]
  },
  {
   "_id": "556c978be20c7cd0087c6f13",
   "username": "alina",
   "music": [
     "Skyharbor"         
   ]
  }
]

Как с объединить объекты в массиве по ключам ('_id') следующим образом (приоритет lodash):

[ {
   "_id": "556c978be20c7cd0087c6f10",
   "username": "ivan",
   "music": [
     "Metallica"
   ],
   "interests": [
     "Music",
     "Djent"
   ]
  },
  {
   "_id": "556c978be20c7cd0087c6f13",
   "username": "alina",
   "music": [
     "Skyharbor"         
   ]
   "interests": [
     "Music",
     "Literature"
   ]
  }
]

1 ответ 1

2

Сгруппировать по идентификаторам можно с помощью groupBy, а затем объединить пары с помощью merge:

var users = [{
  "_id": "556c978be20c7cd0087c6f10",
  "username": "ivan",
  "music": [ "Metallica" ]
}, {
  "_id": "556c978be20c7cd0087c6f10",
  "username": "ivan",
  "interests": [ "Music", "Djent" ]
}, {
  "_id": "556c978be20c7cd0087c6f13",
  "username": "alina",
  "interests": [ "Music", "Literature" ]
}, {
  "_id": "556c978be20c7cd0087c6f13",
  "username": "alina",
  "music": [ "Skyharbor" ]
}];

console.log(
  _.map(
    _.groupBy(
      users,
      function (u) { return u._id }
    ),
    function (g) { return _.merge.apply(this, g) }
  )
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js"></script>

P. S. Прошу ногами не бить, в первый раз в жизни вижу lodash.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.