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.
Below are assumed from the question:
response.data is an ArrayteamMemberteamMember has a prop named customFields which is an ArraynameThe 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
item.teamMember.customFields array using map with element as el and index as i.elt and idx.map((el, i) => ({elt: el, idx: i}))
name matches ByLine (can be changed via parameter matchNameWith).filter(obj => obj.name === matchNameWith)
elt and idx. Since we only require the index, map the array to get only the index..map(obj => obj.idx)
name, simply use the first occurance.[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
byline[0].value