截断对象数组中的文本?

问题描述 投票:1回答:1

所以我有一个对象数组,问题是返回的名称很长。我怎样才能使名称结果看起来像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属性显示工具提示以显示多余的文本?

javascript html arrays
1个回答
1
投票
这取决于一些因素,例如这些对象的来源。如果数据来自服务器,则可以在名称到达客户端之前截断服务器上的名称。如果您无权访问服务器代码,则可以自行截断客户端的名称:

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'赋予需要它的其他位置
© www.soinside.com 2019 - 2024. All rights reserved.