Nilesh
Nilesh

Reputation: 618

How do I get all the values from one column in node js

I have a result set which has rows(first row is heading) and columns (like dataset in .NET). I want to fetch all the values from one column out of from that result set. How can I achieve it. I am doing it by in below way.

if (r.length)//r is my result set {
  r.forEach(element => {
    const featureCode = element.column_name.filter();
    // Here I am trying to fetch column name value from r using for each loop
    return featureCode; 
  }

Am I doing it right or there is a better way to do it?

My result set r is look like below.

Hi,

My data in r will look like below.

[
  {
    "Col1": "abc",
    "Col2": "pqr",
    "Col3": "xyx",
    "Col4": "aaa",
    "Col5": "bbb",
    "Col6": "ccc",
    "Col7": "ddd"
  },
  {
    "Col1": "aaa",
    "Col2": "bbb",
    "Col3": "ccc",
    "Col4": "ddd",
    "Col5": "eee",
    "Col6": "fff",
    "Col7": "ggg"
  },
]

Upvotes: 1

Views: 2200

Answers (2)

terrymorse
terrymorse

Reputation: 7086

This is an ideal job for Array.prototype.map():

const r = [{
    Col1: "abc",
    Col2: "pqr",
    Col3: "xyx",
    Col4: "aaa",
    Col5: "bbb",
    Col6: "ccc",
    Col7: "ddd"
  },
  {
    Col1: "aaa",
    Col2: "bbb",
    Col3: "ccc",
    Col4: "ddd",
    Col5: "eee",
    Col6: "fff",
    Col7: "ggg"
  }
];

const colId = "Col5";
const colData = r.map(obj => obj[colId]);

console.log({ colData });
// { colData: [ 'bbb', 'eee' ] }

Upvotes: 1

ROOT
ROOT

Reputation: 11622

Here is a way to loop through the array result and retrieve the value you want, just replace Col1, this is browser javascript but it will work for Node.js too.

const r = [
  {
    "Col1": "abc",
    "Col2": "pqr",
    "Col3": "xyx",
    "Col4": "aaa",
    "Col5": "bbb",
    "Col6": "ccc",
    "Col7": "ddd"
  },
  {
    "Col1": "aaa",
    "Col2": "bbb",
    "Col3": "ccc",
    "Col4": "ddd",
    "Col5": "eee",
    "Col6": "fff",
    "Col7": "ggg"
  },
]
let temp= [];

if (r.length) {//r is my result set {
  r.forEach(({Col1}) => console.log(Col1));
}

// or this
if (r.length) {//r is my result set {
  r.forEach((elem) => consolelog(elem.Col1));
}

// or this

if (r.length) {//r is my result set {
  r.forEach(({Col1}) => temp.push(Col1));
}

console.log(temp)

Upvotes: 1

Related Questions