Home > OS >  How does one retrieve all values from a specific named column from an array of table row like object
How does one retrieve all values from a specific named column from an array of table row like object

Time:03-06

The following variable refers to a table like object structure.

const jstable = [{
  "date": "2022-02-08",
  "new_cases": "23100",
  "deaths": "75",
  "recovered": "30294"
}, {
  "date": "2022-03-01",
  "new_cases": "25854",
  "deaths": "78",
  "recovered": "25548"
}];

I need to store/push e.g. all values of column date into another array. How could this be achieved?

CodePudding user response:

While you can do this with a loop and a collector array, the cleanest way to do it is with map:

let dates = jstable.map(row => row.date);

However, if you need to create arrays for multiple columns, map is not the best function to use because it will have to run through the array multiple times, once for each column you are trying to get.

CodePudding user response:

You can loop through all the elements and get the right attribute.

const jstable = [{"date":"2022-02-08","new_cases":"23100","deaths":"75","recovered":"30294"},{"date":"2022-03-01","new_cases":"25854","deaths":"78","recovered":"25548"}];

function col(array, column){
  let result = [];

  for (let item of array) {
    result.push(item[column]);
  }
  return result;
}

console.log(
  col(jstable, 'date')
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

And col(jstable, 'date') would get you all the date column values.

CodePudding user response:

JSON.parse(jstable).map(row => row.date);

Is this what you're looking for?

  • Related