Array of objects check if it includes key value pair; on which position - Javascript [duplicate]

我的梦境 提交于 2021-01-29 07:22:18

问题


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:


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.




回答2:


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)



回答3:


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!



来源:https://stackoverflow.com/questions/53971269/array-of-objects-check-if-it-includes-key-value-pair-on-which-position-javasc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!