Mr B
Mr B

Reputation: 109

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 :

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 :

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. And use it under the full name div.

I tried several codes but they didn't work. Would appreciate if anyone can help.

Upvotes: 2

Views: 134

Answers (2)

Mr B
Mr B

Reputation: 109

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

byline[0].value

Upvotes: 0

jsN00b
jsN00b

Reputation: 3691

Below are assumed from the question:

  1. response.data is an Array
  2. Each element in this Array is an object
  3. Each such object has a prop named teamMember
  4. Each teamMember has a prop named customFields which is an Array
  5. Each element of the Array (at point 4 above) has a prop name

The objective is to filter only those elments from customFields array where the element's name prop matches the value 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.

Explanation

  • Iterate through the item.teamMember.customFields array using map with element as el and index as i.
  • For each element in the array, return an object with two props namelyelt and idx

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

  • In the resulting array, apply the filter and keep only those elements where name matches ByLine (can be changed via parameter matchNameWith)

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

  • Now, we have an array with objects that have the two props elt and idx. Since we only require the index, map the array to get only the index.

.map(obj => obj.idx)

  • In case there were more than 1 elements that had 'ByLine' as the name, simply use the first occurance.

[0]

Upvotes: 2

Related Questions