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.
CodePudding user response:
Below are assumed from the question:
response.datais an Array- Each element in this Array is an object
- Each such object has a prop named
teamMember - Each
teamMemberhas a prop namedcustomFieldswhich is an Array - 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.customFieldsarray usingmapwith element aseland index asi. - For each element in the array, return an object with two props namely
eltandidx
.map((el, i) => ({elt: el, idx: i}))
- In the resulting array, apply the filter and keep only those elements where
namematchesByLine(can be changed via parametermatchNameWith)
.filter(obj => obj.name === matchNameWith)
- Now, we have an array with objects that have the two props
eltandidx. Since we only require the index,mapthe 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]
CodePudding user response:
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
