Thebeginner
Thebeginner

Reputation: 143

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

Upvotes: 2

Views: 64

Answers (4)

Rohìt Jíndal
Rohìt Jíndal

Reputation: 27202

Try this :

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

var res = arr.filter(obj => obj.a === 1);

console.log(res);

Upvotes: 1

Amardeep Bhowmick
Amardeep Bhowmick

Reputation: 16908

Simple use Array.filter to filter through the object array and select the one having property a === 1

var arr = [{"a":"A","b":"B","c":"C"},{"a":1,"b":2,"c":3},{"a":1,"b":"B","c":"C"}];
const filteredArr = arr.filter(obj => obj.a === 1);
console.log(filteredArr);

Using Array.reduce you can do the same thing:

var arr = [{"a":"A","b":"B","c":"C"},{"a":1,"b":2,"c":3},{"a":1,"b":"B","c":"C"}];
const redArr = arr.reduce((acc, obj) => {
   return acc = obj.a === 1 ? acc.concat(obj) : acc;
}, []);
console.log(redArr);

Using Array.map for this problem is not the right approach, although it is possible:

var arr = [{"a":"A","b":"B","c":"C"},{"a":1,"b":2,"c":3},{"a":1,"b":"B","c":"C"}];
const mapArr = arr.map(obj => obj.a === 1 ? obj : undefined).filter(obj => obj); //hack to remove undefined elements
console.log(mapArr);

Upvotes: 3

Jack Bashford
Jack Bashford

Reputation: 44107

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
}));

Upvotes: 4

holydragon
holydragon

Reputation: 6728

console.log([{
    a: 'A',
    b: 'B',
    c: 'C',
  },
  {
    a: 1,
    b: 2,
    c: 3,
  },
  {
    a: 1,
    b: 'B',
    c: 'C'
  }
].filter(o => o.a === 1))

Upvotes: 1

Related Questions