0

I try to check if an array of object has a key value pair with the key service_tags and a value of an array including the string "trace". If this array has it, I also want to return the position of the object.

My try returns undefined.

gg.fields =
[  
    { ... },
    {value: "D", display_name: "Nat."},
    {  
       "value":"Likes redwine",
       "display_name":"Trace 2",
       "servicio_tags":[  
          "trace"
       ]
    }
 ]


 //function    

 let traceFieldExists = gg.fields.forEach((field, positionOfTraceField) => {
        if (field.servicio_tags && field.servicio_tags[0] === 'trace') {
            return {
              positionOfTraceField : positionOfTraceField,
              exists : true
            };
          } else {
            return {exists : false};
        }
      });

Thanks for the help!

  • 1
    *"Foreach returns void"* JavaScript has no `void` type (it does, bizarrely, have an operator by that name). `Array.prototype.forEach` returns `undefined`. – T.J. Crowder Dec 29 '18 at 16:27
  • Yes I tried to make my title more specific now. Thanks for the comment. –  Dec 29 '18 at 16:28

3 Answers3

0

I try to check if an array of object has a key value pair with the key service_tags and a value of an array including the string "trace"

forEach doesn't do that. It always returns undefined. If you just want to know if such an entry exists, use some. If you want to retrieve the first matching entry, use find. If you want the index of the first matching entry, use findIndex.

Your edit adds "on which position" to the title, which makes me think you want findIndex:

let traceFieldIndex = gg.fields.findIndex(field => {
    return field.servicio_tags && field.servicio_tags[0] === 'trace';
});

traceFieldIndex will contain the index of the first entry in the array for which the callback returned a truthy value, or -1 if the full array was processed and the callback never returned a truthy value.

If field.servicio_tags might have 'trace' but not at index 0, you might want includes there:

let traceFieldIndex = gg.fields.findIndex(field => {
    return field.servicio_tags && field.servicio_tags.includes('trace');
});

That will search all the entries in field.servicio_tags instead of just looking at the first one.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    Thanks @T.J. Crowder I used your suggested example. It works great! –  Dec 29 '18 at 16:42
0

According to mdn forEach return an undefined. SO get the index where the condition is matched you can use reduce function

let ggFields = [{
    'value': "D",
    'display_name': "Nat."
  },
  {
    "value": "Likes redwine",
    "display_name": "Trace 2",
    "servicio_tags": [
      "trace"
    ]
  }
]


let k = ggFields.reduce(function(acc, curr, index) {
  if (curr.hasOwnProperty('servicio_tags') && curr.servicio_tags.includes('trace')) {
    acc.push(index)

  }

  return acc;

}, [])
console.log(k)
brk
  • 48,835
  • 10
  • 56
  • 78
0

Other solutions are great too, but here's one using .map, which will return something for every value in the array, that gets run through the if condition first:

const gg = {};
gg.fields =
[  
  {value: "D", display_name: "Nat."},
  {  
     "value":"Likes redwine",
     "display_name":"Trace 2",
     "servicio_tags":[  
        "trace"
     ]
  }
]


const traceFieldExists = gg.fields.map((field, inx) => {
  if (field.servicio_tags && field.servicio_tags[0] === 'trace'){
    return {
      positionOfTraceField : inx,
      exists : true
    };
  } else {
    return {
      exists: false
    }
  }
});
console.log(traceFieldExists)

Cheers!

JSONaLeo
  • 416
  • 6
  • 11