Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get an element object of an array from a key name

I'm parsing a csv fils to json with node-csvtojson and I got a JSONarray with the following code

csv({delimiter: ';'}).fromFile(path).then((jsonObj)=>{
    data = jsonObj;
    console.log(jsonObj);
})

with a csv like

a,b,c
A,B,C
1,2,3
1,B,C

I have got

[
{
 a: A,
 b: B,
 c: C,
},
{
 a: 1,
 b: 2,
 c: 3,
},
{
 a: 1,
 b: B,
 c: C
}
]

But I want to find every object who has the element a === 1 and I want to have all the content of the object,

like this:

{
 a: 1,
 b: 2,
 c: 3,
},
{
 a: 1,
 b: B,
 c: C,
}

But I 'm struggling to do that, I have tried with array.filter but without success then I have tried to do this with array.map but I got lost on how to do.

Do you have any idea on or I could do that ?

Than you

like image 660
Thebeginner Avatar asked Dec 30 '25 04:12

Thebeginner


1 Answers

Use Array.filter like so:

const data = [{
    a: 'A',
    b: 'B',
    c: 'C',
  },
  {
    a: 1,
    b: 2,
    c: 3,
  },
  {
    a: 1,
    b: 'B',
    c: 'C'
  }
];

console.log(data.filter(({ a }) => a == 1));

If you want this to work with old browsers, here's an ES5-compliant version:

var data = [{
    a: 'A',
    b: 'B',
    c: 'C',
  },
  {
    a: 1,
    b: 2,
    c: 3,
  },
  {
    a: 1,
    b: 'B',
    c: 'C'
  }
];

console.log(data.filter(function(obj) {
  return obj.a == 1
}));
like image 153
Jack Bashford Avatar answered Dec 31 '25 16:12

Jack Bashford