0

Why my code is not count?

var a = {
  count: [{label:'a', value: 'a'}],
  next: [{label:'b', value: 'b'}],
  previous: [{label:'c', value: 'c'}],
}

function get_item() {

  var x = "a"

  for (let item in a){
    a[item].forEach(obj => {
      console.log(obj.value, x )   
      if(obj.value === x) {
        return item
      }
    })
  }
}


console.log(get_item())

the console logs are bellow:

a a
b a
c a
undefined

you see the a a, but why it do not is the count rather than undefined?

sof-03
  • 2,255
  • 4
  • 15
  • 33

2 Answers2

1

below solution may work for you:

 var a = {
        count: [{label:'a', value: 'a'}],
        next: [{label:'b', value: 'b'}],
        previous: [{label:'c', value: 'c'}]
       }
    function get_item() {
           var x = "a"
           for (let item in a){
            let resultItem = a[item].find((obj)=>{ return obj.value === x });
            if(resultItem) return item //you can also return 'resultItem';
            }
          }
          console.log(get_item())
Azeem Chauhan
  • 407
  • 5
  • 8
0

change your function as such.

var a = {
  count: [{label:'a', value: 'a'}],
  next: [{label:'b', value: 'b'}],
  previous: [{label:'c', value: 'c'}],
}

function get_item() {

  var x = "w"
  var retItem = undefined
  for (let item in a){
    a[item].forEach(obj => {  
      if(obj.value === x) {
        retItem = item
      }
    })
  }
  return retItem;
}


console.log(get_item())

Here we just assign the result into a variable retItem. If we find something we return it, or we just return undefined

Prasanna
  • 4,125
  • 18
  • 41
  • 1
    Just a pointer, `get_item` should return `object | undefined`. Returning `" No result ..."` should be handled by function consuming it. – Rajesh Apr 05 '18 at 10:48