Объединить два массива объектов

Вы можете создать модуль mongoUtil.js, который имеет функции как для подключения к mongo, так и для возврата экземпляра mongo db:

var MongoClient = require( 'mongodb' ).MongoClient;

var _db;

module.exports = {

  connectToServer: function( callback ) {
    MongoClient.connect( "mongodb://localhost:27017/marankings", function( err, db ) {
      _db = db;
      return callback( err );
    } );
  },

  getDb: function() {
    return _db;
  }
};

Чтобы использовать его, вы сделаете это в своем app.js:

var mongoUtil = require( 'mongoUtil' );

mongoUtil.connectToServer( function( err ) {
  // start the rest of your app here
} );

И тогда, когда вам нужен доступ к mongo где-нибудь, вы можете сделать это:

var mongoUtil = require( 'mongoUtil' );
var db = mongoUtil.getDb();

db.collection( 'users' ).find();

Причина этого в том, что в узле, когда модули require 'd, они только загружаются / получаются один раз, так что вы только когда-нибудь закончите с одним экземпляром _db, а mongoUtil.getDb() всегда вернет тот же самый экземпляр.

Примечание, код не проверен.

3
задан Eliya Cohen 16 January 2019 в 16:46
поделиться

4 ответа

Попробуйте этот код

const initial = [
  {name: 'a', times: 40, other: 50},
  {name: 'b', times: 10, other: 15},
  {name: 'c', times: 15, other: 12}
];

const toBeMerged = [
  {name: 'a', times: 45, other: 30},
  {name: 'c', times: 10, other: 10},
  {name: 'd', times: 23, other: 10}
];

//console.log(initial);

function arrayUnique(array) {
    var a = array.concat();
    for(var i=0; i<a.length; ++i) {
        for(var j=i+1; j<a.length; ++j) {
            if(a[i].name === a[j].name)
            {
                a[i].times +=a[j].times;
                a[i].other +=a[j].other;
                a.splice(j--, 1);
            }
        }
    }

    return a;
}


    // Merges both arrays and gets unique items
var array = arrayUnique(initial.concat(toBeMerged));
console.log(array);

0
ответ дан Mohammad Ali Rony 16 January 2019 в 16:46
поделиться

Вы можете сделать это с помощью , уменьшить .

  1. Сначала объедините оба массива, используя concat.
  2. Теперь в объединенном массиве с помощью reduce мы проверяем, присутствует ли свойство объекта в output, чем добавляем times и other в существующее свойство, если нет, то добавляем новое свойство.

const initial= [{name: 'a', times: 40, other: 50},{name: 'b', times: 10, other: 15},{name: 'c', times: 15, other: 12}];
const toBeMerged= [{name: 'a', times: 45, other: 30},{name: 'c', times: 10, other: 10},{name: 'd', times: 23, other: 10}];
let temp = initial.concat(toBeMerged)

let op = temp.reduce((output,current)=>{
  if( output[current.name] ){
    output[current.name].times += current.times
    output[current.name].other += current.other
  } else{
    output[current.name] = current;
  }
  return output;
},{})

console.log(Object.values(op))

0
ответ дан Code Maniac 16 January 2019 в 16:46
поделиться

Здесь у вас есть один подход, использующий redu () и findIndex () для нового массива, который будет объединен. Если новый объект, который должен быть объединен, уже существует (т. Е. Свойство name соответствует некоторому объекту), мы увеличиваем остальные соответствующие свойства и добавляем несуществующие, в противном случае мы передаем весь новый объект:

[ 117]
const initial = [
  {name: 'a', times: 40, other: 50},
  {name: 'b', times: 10, other: 15},
  {name: 'c', times: 15, other: 12}
];

const toBeMerged = [
  {name: 'a', times: 45, other: 30, another: 76},
  {name: 'c', times: 10, other: 10},
  {name: 'd', times: 23, other: 10}
];

let newArray = toBeMerged.reduce((res, curr) =>
{
    let found = res.findIndex(x => x.name === curr.name);

    if (found >= 0)
    {
        res[found] = Object.keys(curr).reduce((r, c) =>
        {
           r[[c]] = (r[[c]] && c !== 'name') ? r[[c]] + curr[[c]] : curr[[c]];
           return r;
        }, res[found]);
    }
    else
    {
        res.push(curr);
    }

    return res;

}, initial);

console.log(newArray);

0
ответ дан Shidersz 16 January 2019 в 16:46
поделиться

Использование оператора распространения, деструктуризации, уменьшения массива, значений объекта # и карты

const initial=[{name:'a',times:40,other:50},{name:'b',times:10,other:15},{name:'c',times:15,other:12}];const toBeMerged=[{name:'a',times:45,other:30},{name:'c',times:10,other:10},{name:'d',times:23,other:10}]

const res = [...[...initial, ...toBeMerged]
.reduce((a,{name,times,other})=>{
    const b = a.get(name);
    return a.set(name,{name, times: (b?b.times:0) + times, other: (b?b.other:0) + other});
}, new Map()).values()];

console.log(res);

0
ответ дан kemicofa 16 January 2019 в 16:46
поделиться
Другие вопросы по тегам:

Похожие вопросы: