[英]how to find index of array element by the name of it inside a function?
I have a js function that reads a JSON file and outputs them with a loop:我有一个 js function 读取 JSON 文件并通过循环输出它们:
response.data.forEach((item,index)=>{
items += " <div class='eleman'>"
+ "<img src='"+item.teamMember.profileImageUrl+"' width='100%'>"
+ "<div class='content list'>"
+ "<div class='fullname'>"+item.teamMember.fullName+"</div>"+
...
There is an array on that json called customFields (item.teamMember.customFields) and it could have 0 to 7 indexes, example for one of them should be like: json 上有一个名为 customFields (item.teamMember.customFields) 的数组,它可能有 0 到 7 个索引,其中一个索引的示例应该是:
id : 1202
name : Tags
type : SingleLineText
value : Composer,Music,Pan's Labyrinth
I want to get the value of the index that's name is ByLine.我想获取名为 ByLine 的索引的值。 And use it under the full name div.
并在全名div下使用。
I tried several codes but they didn't work.我尝试了几个代码,但它们都不起作用。 Would appreciate if anyone can help.
如果有人可以提供帮助,将不胜感激。
Below are assumed from the question:以下是从问题中假设的:
response.data
is an Array response.data
是一个数组teamMember
teamMember
的道具teamMember
has a prop named customFields
which is an ArrayteamMember
都有一个名为customFields
的道具,它是一个数组name
name
The objective is to filter only those elments from customFields
array where the element's name
prop matches the value ByLine
.目标是仅从
customFields
数组中过滤元素name
prop 与值ByLine
匹配的那些元素。
One possible way to achieve this:实现这一目标的一种可能方法:
const getIndexOfByLine = (arr = item.teamMember.customFields, matchNameWith = 'ByLine') => (
arr
.map((el, i) => ({elt: el, idx: i}))
.filter(obj => obj.name === matchNameWith)
.map(obj => obj.idx)
[0]
);
NOTE: If more than 1 element has name
as 'ByLine' then only the first index is returned.注意:如果超过 1 个元素的
name
为“ByLine”,则仅返回第一个索引。
Explanation解释
item.teamMember.customFields
array using map
with element as el
and index as i
.map
遍历item.teamMember.customFields
数组,其中元素为el
,索引为i
。elt
and idx
elt
和idx
.map((el, i) => ({elt: el, idx: i}))
name
matches ByLine
(can be changed via parameter matchNameWith
)name
与ByLine
匹配的那些元素(可以通过参数matchNameWith
更改) .filter(obj => obj.name === matchNameWith)
elt
and idx
.elt
和idx
的对象的数组。 Since we only require the index, map
the array to get only the index.map
数组只获取索引。 .map(obj => obj.idx)
name
, simply use the first occurance.name
,只需使用第一次出现。 [0]
I used this and it worked我用了这个,它奏效了
let byline=item.teamMember.customFields.filter(checkbyline);
function checkbyline(fields) {
if (fields.name == 'Byline') {
return fields.value}
else {return }
}
and to use it on the HTML output并在 HTML output 上使用它
byline[0].value
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.