Compare 2 arrays and create a new array if they have the same Id

Asked

Viewed 790 times

2

I have 2 arrays:

array1 = [
...
  {
   "id_projeto": 4,
   "sigla": "ADM-APR",
   "nome": "Administração APR",
   "descricao": null,
   "atividades": [ 13, 14, 49, 80, 81, 82 ] // id
  }
...
];

array2 = [
...
  }
    "id_atividade": 49, //id
    "codigo": "P46",
    "nome": "Treinamento de Instalação e Manutenção",
    "data_inicio": "2017-04-01",
    "data_fim": "2017-04-30",
    "prioridade": "1 ",
  },
  }
    "id_atividade": 50, //id
    "codigo": "P47",
    "nome": "Manutenção das estações",
    "data_inicio": "2017-04-01",
    "data_fim": "2017-04-30",
    "prioridade": "1 ",
  }
...
];

I have to create a new array with the activities(array2) of each project(array1), it would look like this:

array3 = [
...
  {
    "sigla": "ADM-APR",
    "nome_projeto": "Administração APR",
    "descricao": null,
    "id_atividades": [ 13, 14, 49, 80, 81, 82 ],
    "atividades": [
      {
       "id_atividade": 49,
       "codigo": "P46",
       "nome": "Treinamento de Instalação e Manutenção",
       "data_inicio": "2017-04-01",
       "data_fim": "2017-04-30",
       "prioridade": "1 ",
      },
      ...
    ]
  }
...
];

array3 = array1.atividades.map(obj => {
        array2(ativ => {
            if(obj == ativ.id_atividade){
                return console.log(ativ)
            }
        })
    });

When returning the result in the console.log, the answer is the expected one, when returning the answer the array receives the correct number of activities, but, Undefined.

1 answer

2


You can copy each object into the array to avoid changing data outside of this mapping, and then map the property atividades one to one searching in array2 by the corresponding object using the .find() which returns the element that checks the condition iterado.id_atividade == id_procurada.

var array1 = [{
  "id_projeto": 4,
  "sigla": "ADM-APR",
  "nome": "Administração APR",
  "descricao": null,
  "atividades": [13, 14, 49, 80, 81, 82] // ids
}];

var array2 = [{
    "id_atividade": 49, //id
    "codigo": "P46",
    "nome": "Treinamento de Instalação e Manutenção",
    "data_inicio": "2017-04-01",
    "data_fim": "2017-04-30",
    "prioridade": "1 ",
  },
  {
    "id_atividade": 50, //id
    "codigo": "P47",
    "nome": "Manutenção das estações",
    "data_inicio": "2017-04-01",
    "data_fim": "2017-04-30",
    "prioridade": "1 ",
  }
];

var array3 = array1.map(obj => {
  const novoObjecto = JSON.parse(JSON.stringify(obj)); // cria uma cópia
  novoObjecto.id_atividades = novoObjecto.atividades; // guardar a array de IDs original
  novoObjecto.atividades = novoObjecto.atividades.map(id => array2.find(el => el.id_atividade == id));
  return novoObjecto;
});

console.log(array3);

Using the second example of your code would look like this:

const atividadesList = [{
    "id_atividade": 1,
    "codigo": "P1",
    "nome": "Operação SEMANAL do marégrafo convencional da EMFOR (CE)",
    "data_inicio": "2017-01-01",
    "data_fim": "2017-01-31",
    "prioridade": "1 "
  },
  {
    "id_atividade": 39,
    "codigo": "P1",
    "nome": "Operação SEMANAL do marégrafo convencional da EMFOR (CE)",
    "data_inicio": "2017-02-01",
    "data_fim": "2017-02-28",
    "prioridade": "1 "
  },
  {
    "id_atividade": 6,
    "codigo": "P1",
    "nome": "Operação SEMANAL do marégrafo convencional da EMFOR (CE)",
    "data_inicio": "2017-06-01",
    "data_fim": "2017-06-30",
    "prioridade": "1 "
  },
  {
    "id_atividade": 32,
    "codigo": "P1",
    "nome": "Operação SEMANAL do marégrafo convencional da EMFOR (CE)",
    "data_inicio": "2017-07-01",
    "data_fim": "2017-07-31",
    "prioridade": "1 "
  },
  {
    "id_atividade": 28,
    "codigo": "P1",
    "nome": "Operação SEMANAL do marégrafo convencional da EMFOR (CE)",
    "data_inicio": "2017-08-01",
    "data_fim": "2017-08-31",
    "prioridade": "1 "
  },
  {
    "id_atividade": 19,
    "codigo": "P1",
    "nome": "Operação SEMANAL do marégrafo convencional da EMFOR (CE)",
    "data_inicio": "2017-09-01",
    "data_fim": "2017-09-30",
    "prioridade": "1 "
  }
];

const atividadesId = [10, 19, 28];


const atividades = atividadesId.map(
  id => atividadesList.find(obj => obj.id_atividade == id) || {}
);

  • I’m trying to do this within a mutations in vuex, I haven’t succeeded yet, but it has given me some idea. Vlw ! Do you have any tips for article, tutorial, video, anything that helps me work better with javascript arrays ? I always have trouble with that.

  • @mtAlves if you’re using Vue.js/Vuex explains the question better. Shows how the actions and the mutations and what you want to do. If each ID is searched by ajax the corresponding element you should do in actions for the mutations shall only have synchronous code.

  • Actually I’m starting to use vuex now and I started with web development will be 3 months, so it’s all kind of messy and I’m still kind of lost kk, but give a look at github.com/mtAlves/Pta

  • @mtAlves I use Vue at work and I think it’s great. I don’t think this question will make you understand everything. Is the app great? Do you really need Vuex? It might be easier to start without Vuex...

  • An average app, but maybe it’ll get big. I’m not sure if I need Vuex, but as I’m trying to learn, I found it interesting to start using it. And yes, Vue is excellent, I had never written a line of css 3 months ago and I can already develop something, even if giving headbutt kkk

  • @mtAlves ok. So I suggest you ask here step by step, there are more people here who also know about Vue.js and can help. Regarding the question, say what you could not use/understand to get this problem solved.

  • I did, but the.log console prints the expected result, but the data is Undefined. I will edit the question to better view.

  • @mtAlves in this case you have an asynchronous condition that you are not respecting.

  • @mtAlves have just seen your Edit. You are not using my code. Put here a jsFiddle with all that code that I can take a look at and fix

  • I couldn’t do it in jsFiddle, if I could just look at the code later on github (https://github.com/mtAlves/pta/blob/master/src/store/mutations.js), I went up the fake file using json-server tb (server.json). I’ll get some sleep. But thanks for the force anyway.

  • @mtAlves then in case there is no ID you want to return '' or {}. Return {} or remove from the array seems more correct than return ''

  • I did in pythontutor https://goo.gl/Z3oUFW even looking frame by frame I can’t understand pq return Undefined, I expected to return the whole object.

  • @mtAlves saw my last question here?

  • @mtAlves edited the answer with a new example, I used an empty object when not finding

  • Funcionouuuuuuuuu, I think I love you man. I hadn’t thought about find(). Thank you really!!

  • @mtAlves great. I had used the find in the first example I had given, but now with the second example perhaps it has become clearer. I am glad to help :)

Show 11 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.