Reputation: 1923
I want to console.log
a value within an array of objects based on another specific value. For example, I have a simple array of objects. For all of the objects with v: 1, I want to print the z value.
var array = [
{v:1, z: 4},
{v:3, z: 8},
{v:4, z: 6},
{v:1, z: 4},
{v:2, z: 9},
{v:2, z: 3},
{v:4, z: 7},
{v:1, z: 5},
];
I tried something like for (array.v(1) => { console.log(array.z); });
but the syntax isnt correct. What is the correct syntax here?
Upvotes: 0
Views: 29
Reputation: 5648
You need to add a if statement to your for each loop
Also you can use a filter function but this will print the object that meet your filter, not only the z value
var array = [
{v:1, z: 4},
{v:3, z: 8},
{v:4, z: 6},
{v:1, z: 4},
{v:2, z: 9},
{v:2, z: 3},
{v:4, z: 7},
{v:1, z: 5},
];
console.log('For Each')
array.forEach(o=>{ if(o.v == 1)console.log(o.z)})
console.log('Filter')
console.log(JSON.stringify(array.filter(o=>o.v==1)))
Upvotes: 1
Reputation: 1208
Try something like this:
array.forEach( function(a) { if ( a.v == 1 ) console.log(a.z); } );
Upvotes: 2