0

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'
  }
]

Also how do you use html title attribute to have the tooltip show up to show that extra text?

3
  • my bad, missed the second part of your question, updated my answer Commented Nov 6, 2019 at 18:36
  • so loop over it and truncate it. Easy enough with a for each loop Commented Nov 6, 2019 at 20:32
  • @epascarello Could you show a working example if you don't mind please. Commented Nov 6, 2019 at 23:52

1 Answer 1

1

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);

this way, you can give the 'name' to the title attribute, and the 'shortName' to other places that need it

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the response, yes it is coming from a server and i do not have access to the code but when i try your code in this codepen: codepen.io/treehuggerrick/pen/ZEEoYPe?editors=1111. I don't get anything in here so could you check this please.
you have some code errors, try copy, I will update my answer, click on 'run code snippet'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.