Filter the month inside a extracted object with Object.Keys

Asked

Viewed 34 times

0

I am studying React and have made a cash flow application using firebase as database. I would like to perform a query using the "map()" or another way that traversed the object showing only the entries of the month of sea, but I am finding it difficult to accomplish this task, since I am using the query Object.Keys. Below is an example of how the object looks after being extracted.

const keysIn = Object.keys(this.props.inflow);

let entrada =  JSON.stringify(keysIn);


console.log(entrada)

// O retorno do console.log fica assim
 {
    '1': {
      month: 'fev',
      name: 'xxxxxxx',
      value: 300,
    },
    '2': {
      month: 'mar',
      name: 'yyyyyyyy',
      value: 500,
    },
    '3': {
      month: 'mar',
      name: 'zzzz',
      value: 400,
    },
  }
  • But you sure want to use the map and not the filter?

  • It is not necessary not, I thought of them because I need to go through the object and show all that contain the month "sea".

  • Plus it’s kind of weird console.log return an object to the variable entrada since the Objects.keys returns a array. You’re sure of it?

  • In case the input variable receives JSON.stringfy(keysIn), then it becomes an object, I even made one typeof to dispel the doubt .

1 answer

2


In your case you can use the map to form a array and after that use the filter to keep only those who are with mar in the attribute month:

const original = {
  '1': {
    month: 'fev',
    name: 'xxxxxxx',
    value: 300,
  },
  '2': {
    month: 'mar',
    name: 'yyyyyyyy',
    value: 500,
  },
  '3': {
    month: 'mar',
    name: 'zzzz',
    value: 400,
  },
};

// Pega apenas as chaves dos atributos
const chaves = Object.keys(original);
// Transforma o objeto em array baseado nas chaves
const todos = chaves.map((chave) => original[chave]);
// Filtra aqueles com a propriedade month igual a "mar"
const filtrados = todos.filter((item) => item.month === 'mar');

console.log(filtrados);

  • 1

    Thank you, now I understand the logic I needed to make.

Browser other questions tagged

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