所以我有一个对象数组,问题是返回的名称很长。我怎样才能让名字结果看起来像 returnedArray: [ {name:'reallyy..',age:'28',hobby:'blah'},{name:'another..',age:'28 ',爱好:'某事'}]
resultArray: [
{
name: 'realllyyyyyyLongggname',
age: '28',
hobbit: 'blah'
},
{
name: 'anotherrealllyyyyyyLongggname',
age: '28',
hobbit: 'blah'
}
]
另外,如何使用 html 标题属性来显示工具提示以显示额外的文本?
最佳答案
这取决于一些事情,比如这些对象来自哪里。如果数据来自服务器,您可以在服务器端 chop 名称,然后再将其发送到客户端。如果您无权访问服务器代码,您可以自己在客户端 chop 名称:
const maxLength = 50;
const resultArray = [{ ... }].map(i => {
if (i.name <= maxLength) return i;
const shortenedName = i.name.substring(0, maxLength + 1);
i.name = shortenedName + '...';
return i;
});
抱歉,我错过了您提出的第二个问题。如果您希望仍然能够访问全名,则需要修改上面的循环,以便它不会覆盖名称,而是存储短名称的第二个值:
const rawData = [
{
name: 'realllyyyyyyLongggname',
age: '28',
hobbit: 'blah'
},
{
name: 'anotherrealllyyyyyyLongggname',
age: '28',
hobbit: 'blah'
}
];
const maxLength = 10;
const resultArray = rawData.map(i => {
if (i.name <= maxLength) i.shortName = i.name;
else {
const shortenedName = i.name.substring(0, maxLength + 1);
i.shortName = shortenedName + '...';
}
return i;
});
console.log(resultArray);
这样,您就可以将“name”赋予 title 属性,并将“shortName”赋予其他需要它的地方
关于javascript - chop 对象数组中的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58736182/