Anna F
Anna F

Reputation: 1683

How to choose objects from an array of objects with specific attribute

I have an array result2 of Objects, and each Object has attributes. So if I call console.dir(result3); in my console I see Example

I would lie to sort my Objects, for example I need Object with

sm[['_akzsilb'] === 'LV' 
sm ['_graphem'] === 'diphtong']

I tried

const result3 = [];
for (let i = 0; i < result2.length; i++) {
  if (result2[i].sm[['_akzsilb'] === 'LV' && ['_graphem'] === 'diphtong']) {
    result3.push(result2[i]);
  }
}

But it doesnt't work. I guess this is right direction, because if I try something, like

const result3 = [];
for (let i = 0; i < result2.length; i++) {
  if (result2[i].sm) {
    result3.push(result2[i]);
  }
}

it works. So how I could go 'deeper' and access both (I need both, so they both must exist by object) _akzsilb and _graphem

Upvotes: 1

Views: 61

Answers (1)

Will
Will

Reputation: 3241

You can use Array filter.

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Array.prototype.filter()

let arr = [{
    name: "Joe",
    rank: "Private",
    serialnum: 1
  },
  {
    name: "Bob",
    rank: "General",
    serialnum: 4
  },
  {
    name: "Kev",
    rank: "Private",
    serialnum: 6
  },
  {
    name: "Kel",
    rank: "Private",
    serialnum: 3
  }
];

let results = arr.filter(person => person.rank === "Private" && person.serialnum != 6);

console.log(results);

Upvotes: 1

Related Questions