-3

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>
DanielHas
  • 13
  • 1
  • 3
    What is the question? – Smit Feb 27 '17 at 18:23
  • Possible duplicate of [Get JavaScript object from array of objects by value or property](http://stackoverflow.com/questions/13964155/get-javascript-object-from-array-of-objects-by-value-or-property) – Sebastian Simon Feb 27 '17 at 18:26

3 Answers3

0
<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.b == z;})).a;
}
</script>

</body>

You just needed to add .b to your find age.

Smit
  • 2,078
  • 2
  • 17
  • 40
0

I mean, there are a couple of issues here, but the first one I noticed was this line:

 document.getElementById("demo")

You have no element with the id "demo".

Smit's answer below is also correct. There were multiple issues here.

chrispy
  • 3,552
  • 1
  • 11
  • 19
0

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>
kind user
  • 40,029
  • 7
  • 67
  • 77