DanielHas DanielHas -4 years ago 94
Javascript Question

Array.find searching by a specific value

i have a local variable that i want to find by him ..



<body>
<button onclick="myFunction()">Try it</button>
<script>
var ages = [{a:"danielhason",b:"1"},{a:"aanielhason",b:"2"},{a:"banielhason",b:"3"),{a:"zanielhason",b:"4"}];
var z = "1";

function myFunction() {
document.getElementById("demo").innerHTML = (ages.find(function (age) { return age == z;})).a;
}
</script>
</body>




Answer Source

Since ages is an array of objects, you have to iterate over it. Let's say that v is every object inside ages array. Then, you have to use a condition, if v.b is equal to z value (1) - log that object a value - v.a.

Note: Keep your code clean, use line breaks.

var ages = [{
  a: "danielhason",
  b: "1"
}, {
  a: "aanielhason",
  b: "2"
}, {
  a: "banielhason",
  b: "3",
}, {
  a: "zanielhason",
  b: "4"
}];

function myFunction(ages) {
  var z = "1";
  ages.find(function(v) {
    if (v.b == z) {
      console.log(v.a)
    }
  })
}

myFunction(ages);
<button onclick="myFunction(ages)">Try it</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download