簡體   English   中英

如何通過 function 中的名稱查找數組元素的索引?

[英]how to find index of array element by the name of it inside a function?

我有一個 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>"+

    ...

json 上有一個名為 customFields (item.teamMember.customFields) 的數組,它可能有 0 到 7 個索引,其中一個索引的示例應該是:

id    : 1202
name  : Tags
type  : SingleLineText
value : Composer,Music,Pan's Labyrinth

我想獲取名為 ByLine 的索引的值。 並在全名div下使用。

我嘗試了幾個代碼,但它們都不起作用。 如果有人可以提供幫助,將不勝感激。

以下是從問題中假設的:

  1. response.data是一個數組
  2. 這個數組中的每個元素都是一個 object
  3. 每個這樣的 object 都有一個名為teamMember的道具
  4. 每個teamMember都有一個名為customFields的道具,它是一個數組
  5. Array 的每個元素(在上面的第 4 點)都有一個道具name

目標是僅從customFields數組中過濾元素name prop 與值ByLine匹配的那些元素。

實現這一目標的一種可能方法:

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]
);

注意:如果超過 1 個元素的name為“ByLine”,則僅返回第一個索引。

解釋

  • 使用map遍歷item.teamMember.customFields數組,其中元素為el ,索引為i
  • 對於數組中的每個元素,返回一個 object 和兩個 props,即eltidx

.map((el, i) => ({elt: el, idx: i}))

  • 在結果數組中,應用過濾器並僅保留nameByLine匹配的那些元素(可以通過參數matchNameWith更改)

.filter(obj => obj.name === matchNameWith)

  • 現在,我們有一個包含兩個道具eltidx的對象的數組。 由於我們只需要索引, map數組只獲取索引。

.map(obj => obj.idx)

  • 如果有多個元素以 'ByLine' 作為name ,只需使用第一次出現。

[0]

我用了這個,它奏效了

let byline=item.teamMember.customFields.filter(checkbyline);


function checkbyline(fields) {
  if (fields.name == 'Byline') {
  return fields.value}
else {return }
}   

並在 HTML output 上使用它

byline[0].value

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM