1

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.

7
  • Can you give examples of the actual file names Commented Jan 20, 2019 at 15:05
  • You want to check the documentation of the 3rd-party script I guess. Based on the information in your question we won't be much help. Commented Jan 20, 2019 at 15:05
  • @Andy, the documentation doesn't show you how to do it the way I want to do it which is to submit via Ajax. Commented Jan 20, 2019 at 15:05
  • @AshayMandwarya, those are the actual file names. Anything you upload is renamed with random characters like that ie: gIpVCEAe4eiW.jpg Commented Jan 20, 2019 at 15:06
  • Is your question, how do I remove 0:/ from the the values? Commented Jan 20, 2019 at 15:08

2 Answers 2

5

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

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

7 Comments

That's beautiful.
@Andy, that is working nicely, thank you. I am trying to insert this into mongo db but it is inserting it like gIpVCEAe4eiW.jpg, 5yA9n2IfNh65.jpg. Would I need to do something like destructuring in order to get each file name individually and not in an array?
@Andy, my database format is basically images: [ { name: { type: String } } ]
@Andy, fair enough. Will fiddle around and ask another question if necessary. Thanks for your answer, it was most helpful.
The promises code might look something like this.
|
1

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(', '));

Comments

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.