问题描述
所以我有一个对象数组,问题是返回的名称很长。我怎样才能让名字结果看起来像 returnedArray:[{name:'reallyy ..',age:'28',hobby:'blah'},{name:'another ..',age :'28',hobby:'something'}]
so i have an array of objects and the issue is that the names being returned are quite long. How can i have the names result look like returnedArray: [ {name:'reallyy..',age:'28',hobby:'blah'},{name:'another..',age:'28',hobby:'something'} ]
resultArray: [
{
name: 'realllyyyyyyLongggname',
age: '28',
hobbit: 'blah'
},
{
name: 'anotherrealllyyyyyyLongggname',
age: '28',
hobbit: 'blah'
}
]
另外,您如何使用html title属性来显示工具提示
Also how do you use html title attribute to have the tooltip show up to show that extra text?
推荐答案
这取决于一些因素,例如这些对象的来源。如果数据来自服务器,则可以在名称到达客户端之前截断服务器上的名称。如果您无权访问服务器代码,则可以自己截断客户端的名称:
This depends on a few things like where these objects are coming from. If the data is coming from a server, you can truncate the names on the server side before they get to the client side. If you don't have access to the server code, you can truncate truncate the names on the client side yourself:
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;
});
对不起,我错过了您遇到的第二个问题。如果您仍然希望访问全名,则需要修改上面的循环,以免覆盖名称,而是为短名称存储第二个值:
Sorry, I missed the second question you had. If you want to be able to still access the full name, you'll need to modify the loop above so that it doesn't overwrite the name, but instead, store a second value for short name:
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);
这样,您可以将名称指定为title属性,并将 shortName指向需要此属性的其他地方
this way, you can give the 'name' to the title attribute, and the 'shortName' to other places that need it
这篇关于在对象数组中截断文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!