对象数组检查它是否包含键值对;在哪个位置-Javascript [英] Array of objects check if it includes key value pair; on which position - Javascript
问题描述
我尝试检查对象数组是否具有带有键 service_tags
的键值对和包含字符串"trace"的
.如果这个数组有它,我也想返回对象的位置. array
的值
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.
我的尝试返回 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};
}
});
感谢您的帮助!
推荐答案
我尝试检查对象数组是否具有带有键service_tags的键值对和包含字符串"trace"的数组值
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
不这样做.它总是返回未定义
.如果您只想是否存在此类条目,请使用 查找
.如果要第一个匹配条目的 index ,请使用
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
.
您的编辑在标题上添加了在哪个位置",这使我认为您想要 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
将包含数组中回调为其返回真值的第一个条目的索引,如果处理了完整数组和回调,则为 -1
从未返回真实值.
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.
如果 field.servicio_tags
可能具有'trace'
而不是索引0,则可能需要
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');
});
这将搜索 field.servicio_tags
中的所有条目,而不仅仅是查看第一个条目.
That will search all the entries in field.servicio_tags
instead of just looking at the first one.
这篇关于对象数组检查它是否包含键值对;在哪个位置-Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!