Reputation: 277
Hi all I have following code: my code
In this scenario I am receiving some data from backend
const fileName =
[ { id: 1, title: 'Armenia lorem ipsum 15 - Oct 30.pdf' }
, { id: 2, title: 'France lorem ipsum 16 - Nov 30.pdf' }
, { id: 3, title: 'German lorem ipsum 17 - Dec 30.pdf' }
, { id: 4, title: 'English lorem ipsum 18 - Jan 08.pdf' }
]
I am counting if all titles chars sum is greater than 40 then I am hiding rest elements(in my case titles) and showing with numbers. That part works very good.
let lengthCount = 0;
let maxIndex = 0;
const allowCharCount = 40;
const file = [];
const File = ({ data }) => {
data.map((item, index) => {
if (lengthCount <= allowCharCount) {
maxIndex = index;
file.push(item);
}
lengthCount = lengthCount + item.title.length;
});
let myFiles = file.map((perFile) => (
<span key={perFile.id} className="skillItem">
{perFile.title}
</span>
));
return (
<div className="skillWrapper">
<div>{myFiles}</div>
{lengthCount < 20 ? null : (
<div className="skillNumber">+{data.length - maxIndex - 1}</div>
)}
</div>
);
Now I am trying to get each elements title and transform them in this way: I need to get 5 chars from beginning then concatenate "..." and then concatenate 10 chars from the end.
I try to substr my title from the beginning and from the end but it not working
"TypeError: titleFullName.substr is not a function"
here what I try:
let titleFullName = file.map((item) => item.title);
let titleFullNameFirstPart = titleFullName.slice(0, 5);
const titleFullNameSecondPart = titleFullName.slice(10,titleFullName.length - 1);
const TitleName = titleFullNameFirstPart + "..." + titleFullNameSecondPart;
In the end, for each title I should get something like this, for example :
Armen... Oct 30.pdf
Franc... Nov 30.pdf
Germa... Dec 30.pdf
Engli... Jan 08.pdf
Upvotes: 2
Views: 46
Reputation: 370699
Since you want to transform the array, you should put the string transformation logic inside the .map
, so that every item iterated over gets transformed. Your titleFullNameSecondPart
also needs to be tweaked a bit, subtract 10 from the string length and pass it to .slice
to get the last 10 characters.
const fileName = [{
id: 1,
title: "Armenia lorem ipsum 15 - Oct 30.pdf"
},
{
id: 2,
title: "France lorem ipsum 16 - Nov 30.pdf"
},
{
id: 3,
title: "German lorem ipsum 17 - Dec 30.pdf"
},
{
id: 4,
title: "English lorem ipsum 18 - Jan 08.pdf"
}
];
const transformed = fileName.map((item) => {
const titleFullName = item.title;
let titleFullNameFirstPart = titleFullName.slice(0, 5);
const titleFullNameSecondPart = titleFullName.slice(titleFullName.length - 10);
const TitleName = titleFullNameFirstPart + "..." + titleFullNameSecondPart;
return TitleName;
});
console.log(transformed);
Upvotes: 2