How to remove an object from an object array within another object array, in javascript?

Asked

Viewed 2,524 times

4

Hello, I need to return the objs array by eliminating the objects that have the req key === "test" inside the c object array.

Thanks for your help!

const objs = [
  {
    a: "a",
    b: 1,
    c: [
      {
        send: "send",
        req: "req",
        res: "res"
      },
      {
        send: "send",
        req: "teste",
        res: "res"
      }
    ]
  },
  {
    a: "a",
    b: 2,
    c: [
      {
        send: "send",
        req: "req",
        res: "res"
      },
      {
        send: "send",
        req: "teste",
        res: "res"
      }
    ]
  }
];

1 answer

6


First, you need to establish a scheme of what you want to do:

  • You have a array (in response, I will call this array of main array).
  • That one array has several objects inside.
  • These objects have a property c, containing a array object (I’ll call those arrays of secondary arrays).
  • Of the latter array, you want to remove the objects that have the property req with the value teste.

You can solve this in many ways. In this answer, we will approach the solution using the methods map and filter, both present in prototype of Array.

How we are most interested in objects present in the main array, let’s use the method map to iterate on each object of that main array, making some changes. From these changes, map will return a new array.

Within the scope of callback of map, we may modify each child object of the main array, being able to filter the array present on the property c, using the method filter.

Thus (read the comments for a better understanding):

const objs = [{
  a: 'a',
  b: 1,
  c: [
    { send: 'send', req: 'req', res: 'res' },
    { send: 'send', req: 'teste', res: 'res' }
  ]
}, {
  a: 'a',
  b: 2,
  c: [
    { send: 'send', req: 'req', res: 'res' },
    { send: 'send', req: 'teste', res: 'res' }
  ]
}]

// Usando o método `map`, vamos iterar sobre cada objeto do array principal, de
// modo em que seremos capazes de modificar a propriedade (array) `c`, filtrando
// os objetos desse array secundário que possuirem a propriedade `req` definida
// como "teste":
const filteredObjs = objs.map((obj) => {
  // Modificamos somente a propriedade `c`, atribuindo a ela o array secundário
  // filtrado, sem os objetos que possuem `req` definido como "teste".
  //
  // O funcionamento é simples: quando retornamos `false`, o `filter` remove o
  // item da iteração atual. Quando `true` é retornado, o item é mantido.
  obj.c = obj.c.filter((childObj) => {
    if (childObj.req === 'teste') {
      // Retornaremos `false` somente quando `req` for definido como `teste`,
      // removendo esse objeto do array.
      return false
    }

    // Para todos os demais, retorne `true`, mantendo-os no array:
    return true
  })

  // Após filtrarmos a propriedade `c`, devemos retornar o objeto modificado
  // para o método `map`, caso contrário, ele irá criar um array de valores
  // `undefined`:
  return obj
})

console.log(filteredObjs)

Note that the above resolution was very verbose. Making full use of the new features brought by versions superior to ES5, we can rewrite the solution like this:

const objs = [{
  a: 'a',
  b: 1,
  c: [
    { send: 'send', req: 'req', res: 'res' },
    { send: 'send', req: 'teste', res: 'res' }
  ]
}, {
  a: 'a',
  b: 2,
  c: [
    { send: 'send', req: 'req', res: 'res' },
    { send: 'send', req: 'teste', res: 'res' }
  ]
}]

const filteredObjs = objs.map((obj) => ({
  ...obj,
  c: obj.c.filter(({ req }) => req !== 'teste')
}))

console.log(filteredObjs)

Note that, for educational purposes, it is more prudent than the first code snippet is taken into account.


It is important to note that, for a good understanding of this answer, you are slightly familiar with the operation of the methods map and filter.

  • Dude, I was using this logic of mapping and then filtering out element c, but I was getting lost in the logic of return. Thank you so much, you’ve helped too much!

  • :) Anything, the best resource is to go in the MDN documentation. The reference is very complete!

Browser other questions tagged

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