How to pick up specific columns in JS Object

Asked

Viewed 48 times

2

The following code will return me the following result:

/**
 * Dados
 */
let data =
    [
        { data: "01/01/2021", value1: "21", value2: "98" },
        { data: "02/01/2021", value3: "22", value4:  "99"},
        { data: "03/01/2021", value5: "36", value6: "100" }
    ];


/**
 * O header são as keys
 * Pegando apenas os values e inserindo numa lista vázia
 */
let values = [];
values.push(Object.keys(data[0]));
function getValues(data) {
    let arr = [];
    
    for (let i = 0; i < data.length; i++) {
        arr.push(Object.values(data[i]));
    }
    return arr;
}
values = values.concat(getValues(data));

console.log(values);

[
  [ 'data', 'value1', 'value2' ],
  [ '01/01/2021', '21', '98' ],
  [ '02/01/2021', '22', '99' ],
  [ '03/01/2021', '36', '100' ]
]

I need to turn into Whole all values of columns "value1" and "value2". How to obtain only the values of the columns "value1" and "value2" ?

  • You want to modify the table (converting types) or only returning a new array with all values in the numeric type?

  • 1

    It is worth remembering that Object.values does not guarantee any specific output order, so there may be unexpected behavior depending on some situations.

  • return a new array with all values in the numeric type. I am aware of the sort.

  • @Luizfelipe. Object.values guarantees yes the output order which is the same order as the original insertion order. It is documented aqui that The Object.values() method returns an array with the values of the properties of a given object, in the same order provided by the for...in loop and here The for...in loop interacts over enumerated properties of an object in the original insertion order

  • 1

    @Augustovasques, it seems that it is something recent then, because several sources indicate that the order is not guaranteed (and in fact it is what I thought). See here, here, etc... Generally speaking, seeing now, I think from the ES6, the order is indeed guaranteed. But I’m still looking for references in the spec.

  • 1

    See Finding in Ideone. cc: @Augustovasques - I confess I found it strange... But from the JS, we couldn’t expect less, right? : P

  • @Luizfelipe, It’s the order of for...in but in a practical sense it really has no way to rely on the return order of Object.values because if there are numeric keys he puts them in front.

Show 2 more comments

1 answer

2


With the exception of the table header (the first "row"), numerical values are placed in columns two and three (indexed as 1 and 2, respectively).

So, just iterate over all the rows and their respective columns and convert to number the column elements whose index is 1 or 2.

Something like that:

const table = [
  ['data', 'value1', 'value2'],
  ['01/01/2021', '21', '98'],
  ['02/01/2021', '22', '99'],
  ['03/01/2021', '36', '100']
];

const numbers = [];

// Note que começamos a iteração das linhas pelo índice 1 para ignorar o cabeçalho (a primeira linha):
for (let rowIndex = 1; rowIndex < table.length; rowIndex++) {
  const row = table[rowIndex];

  for (let columnIndex = 0; columnIndex < row.length; columnIndex++) {
    if (columnIndex === 1 || columnIndex === 2) {
      const num = parseInt(row[columnIndex], 10);
      numbers.push(num);
    }
  }
}

console.log(numbers);

And of course, if the number of columns is too large, it can end up becoming impractical to maintain a condition in the if for each numeric index. In this case, you can create a set with the numeric indices to be considered:

const table = [
  ['data', 'value1', 'value2'],
  ['01/01/2021', '21', '98'],
  ['02/01/2021', '22', '99'],
  ['03/01/2021', '36', '100']
];

const numberIndexes = new Set([1, 2]); // Índices das colunas numéricas (somente estas serão considerados)
const numbers = [];

for (let rowIndex = 1; rowIndex < table.length; rowIndex++) {
  const row = table[rowIndex];

  for (let columnIndex = 0; columnIndex < row.length; columnIndex++) {
    if (numberIndexes.has(columnIndex)) {
      const num = parseInt(row[columnIndex], 10);
      numbers.push(num);
    }
  }
}

console.log(numbers);

Browser other questions tagged

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