user8463989
user8463989

Reputation: 2459

Strip away characters in array

I am using a 3rd party script for uploading files and when I upload multiple files I get the names in this format:

[{"file":"0:/gIpVCEAe4eiW.jpg"},{"file":"0:/5yA9n2IfNh65.jpg"}]

I just want the actual file names. I wish I could post some code of what I have tried but I can't think of many options. I can't get .split alone to do what I want.

Upvotes: 1

Views: 65

Answers (2)

Andy
Andy

Reputation: 63524

map over the array and return the replaced filename. You'll get a new array back.

const arr = [{"file":"0:/gIpVCEAe4eiW.jpg"},{"file":"0:/5yA9n2IfNh65.jpg"}];

const out = arr.map(obj =>  {
  return obj.file.replace('0:/', '');
});

console.log(out);

Upvotes: 5

PitchBlackCat
PitchBlackCat

Reputation: 555

You can use Array.map to perform a transformation on each element in the array.

First we flatten the array of objects to an array of strings, next we cut off the 0:/ with a split

let files = [{"file":"0:/gIpVCEAe4eiW.jpg"},{"file":"0:/5yA9n2IfNh65.jpg"}]
let result = files
  .map(f => f.file)
  .map(f => f.split('0:/')[1])
  
window.alert(result.join(', '));

Upvotes: 1

Related Questions