1

I am sending an array object which right now looks like this in my console:

[{

}]

but I want to have it like this:

{

}

Could someone tell me how to change it, to my desired form? this is how my documentsArray looks:

  documentsArray = [];

This is how my code looks like this:

uploadFile2(files: FileList | null): void {
        const file = files.item(0)
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          this.documentsArray.push({documentType: this.form.controls.dokumentType.value, file: reader.result})
          console.log(this.documentsArray)
        }
    }

2 Answers 2

1

You can access an array item using the index position:

const foo = [{ bar: 'baz' }, { quz: 'qux' }];

console.log(foo[0]); // only first item: `{ bar: 'baz' }`

I.e.:

uploadFile2(files: FileList | null): void {
        const file = files.item(0)
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => {
          this.documentsArray.push({documentType: this.form.controls.dokumentType.value, file: reader.result});
          // you can use the first object in the array
          console.log(this.documentsArray[0]);
        }
    }

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

4 Comments

would this work for a post request as well?
That depends on the back-end. Is there any documentation available on what that specific end-point accepts? (Either an Array or an single object)
it accepts an single object, but I did not quite understand your example sorry
Elaborated on the answer. Let me know if this helps, otherwise what's unclear.
0

JSON specification is this:

[{ array1 }, {array2}, {other arrays}]

And this is the standard whay, why you would like to go outside the standard method?? Please note that in future if you want excange data with oter platforms, you will rebuild everithing, cause json array is with [ ] and json decode will fail if you don't have it, if you don't know how to handle the [ ] just temporary delete the first and the last characters from the writing/reading string, but is not so good..

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.