javascript - chop 对象数组中的文本?

标签 javascript html arrays

所以我有一个对象数组,问题是返回的名称很长。我怎样才能让名字结果看起来像 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/

相关文章:

html - 移动浏览器忽略 iframe 高度

java - 如何将字符串数组转换为唯一值数组?

javascript - 如何限制输入仅接受数字?

javascript - 为什么我的按钮没有动画?

javascript - 在调用 request.getRequestDispatcher() JSP 之前修改 HTML 内容?

javascript - 通过使用 Javascript 单击图片来更改图片

php - 从mysql数据到json在数组中创建数组

javascript - 按卖家对一系列销售额进行分组,从每个卖家那里获取总数,按总销售额排序

javascript - 返回元素路径的好方法是什么?

javascript - 为什么点击时我的颜色没有变化?