I am trying to add a key-value pair to an array of files. I know that this question is already covered in detail in other articles, e.g. here. However, the approaches used do not work in my context. If I missed something or there is another obvious flaw, please apologize!
I have one or more pictures in an array and would like to add the information to each of these files, whether the picture is a title image or not. I.e. I want to achieve something like this:
[0: {File: {name: "Test",
lastModified: "125344",
etc: "something"},
isTitlePicture: null}
1: {File: {name: "Test",
lastModified: "125344",
etc: "something"},
isTitlePicture: null}]
With my current code I get the array as as displayed below. This means that the information about the title image is inside the file information. This is what I try to avoid.
[0: File: {name: "Test",
lastModified: "125344",
etc: "someting",
isTitlePicture: {isTitlePicture: null}}
1: File: {name: "Test",
lastModified: "125344",
etc: "someting",
isTitlePicture: {isTitlePicture: null}]
import React, { Component } from "react";
import { MDBRow, MDBCol, MDBCardBody, MDBCard, MDBCardImage } from "mdbreact";
export class ImageUploadView extends Component {
constructor(props) {
super(props);
this.state = {
files: [],
images: []
};
}
onChangeImage(e) {
const files = Array.from(e.target.files);
var obj = { isTitlePicture: null };
files.forEach(item => item.isTitlePicture = {...obj});
const images = files.map((file) => URL.createObjectURL(file));
this.setState({
files: [...this.state.files, ...files],
images: [...this.state.images, ...images]
});
}
render() {
return (
<React.Fragment>
<div className="card card-body mt-4 mb-4">
<h1>Add Image</h1>
<div>
<input
type="file"
onChange={(e) => this.onChangeImage(e)}
multiple
//accept=".jpg,.png"
/>
</div>
<div className="Images">
{this.state.images.map((image, i) => (
<MDBRow
key={image}
style={{ margin: "10px", display: "inline-block" }}
>
<MDBCol>
<MDBCard style={{ width: "5rem" }}>
<MDBCardImage
className="img-fluid"
src={image}
waves
/>
<MDBCardBody>
</MDBCardBody>
</MDBCard>
</MDBCol>
</MDBRow>
))}
</div>
</div>
</React.Fragment>
);
}
}
}
Basically I want to have isTitlePicture on the same "level" as File and not within File.