我希望将一个对象的属性/值与类实例合并。(我不确定JS中的正确术语是什么,但下面的示例应该可以说明问题)
我的尝试是使用展开语法。见下文。
我有一个文件实例:
输出类似于:
添加这段代码后,我使用FileReader .readAsText()方法获取内容,并将其包装在对象中,如下所示:
mergedObject是一个文件实例。我假设扩展运算符在处理类实例时与处理对象的方式不同?我该如何实现合并的对象?
我的尝试是使用展开语法。见下文。
我有一个文件实例:
const files = listOfFilesFromDragNdrop();
let file = files[0];
console.log(file)
输出类似于:
File(2398)
lastModified: 1530519711960
lastModifiedDate: Mon Jul 02 2018 10:21:51 GMT+0200
name: "my_file.txt"
preview: "blob:http://localhost:8080/6157f5d5-925a-4e5d-a466-24576ba1bf7c"
size: 2398
type: "text/plain"
webkitRelativePath: ""
添加这段代码后,我使用FileReader .readAsText()方法获取内容,并将其包装在对象中,如下所示:
contentObject = getFileContentFromFile()
console.log(contentObject)
将输出类似于:
{
preview: "blob:http://localhost:8080/6157f5d5-925a-4e5d-a466-24576ba1bf7c",
content: "Lorem ipsum some text here."
}
我希望最终得到合并后的对象:
{
// "preview" is the key used to map files and content
preview: "blob:http://localhost:8080/6157f5d5-925a-4e5d-a466-24576ba1bf7c",
// "text" is the new field with the content from contentObject
text: "Lorem ipsum some text here."
// The other fields are from the File instance
name: "my_file.txt",
size: 2398,
type: "text/plain",
lastModified: 1530519711960,
// ...
}
我最初尝试的方法是:
const mergedObject = {
...file,
text: contentObject.content
}
同样地(注意text
键将变为content
),我尝试了...
const mergedObject = {
...file,
...contentObject
}
但是,我只得到了contentObject
字段,即mergedObject
与contentObject
相似。有趣的是,如果我这样做
const mergedObject = {
...file
}
mergedObject是一个文件实例。我假设扩展运算符在处理类实例时与处理对象的方式不同?我该如何实现合并的对象?
更多非必要信息
FileReader
在redux中间件中实现,并在读取完成后使用{ preview: '1234..ef', text: 'Lorem ipsum'}
对象作为有效负载分派新操作。- 我正在使用
preview
字段将内容映射到文件,并希望以类似于以下方式返回合并的对象:“return files.map(file => file.preview !== payload.preview? file: {...file, text: payload.content}
”
FileReader.readAsText
"获取内容,例如在对象中"。这不会返回一个字符串而不是一个对象吗?也许我误解了某个步骤。 - mccambridge