【发布时间】:2018-12-18 14:31:39
【问题描述】:
我想将对象的属性/值与类实例合并。 (我不确定 JS 中的正确术语是什么,但示例应该澄清)
我的尝试是使用扩展语法。见下文。
我有一个File-instance:
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 是一个 File 实例。我假设扩展运算符对类实例的工作方式与对对象的工作方式不同?如何实现合并的对象?
更多不必要的信息
-
FileReader在 redux 中间件中实现,并在完成读取后以{ preview: '1234..ef', text: 'Lorem ipsum'}对象作为负载分派一个新操作。 - 我正在使用
preview-字段将内容映射到文件,并希望在“文件”-reducer 中返回合并的对象,例如:return files.map(file => file.preview !== payload.preview? file: {...file, text: payload.content}
【问题讨论】:
-
您说您正在使用
FileReader.readAsText“获取内容,例如在对象中”。这不是要返回一个字符串,而不是一个对象吗?也许我误会了一步。 -
你是对的,但它是异步的,所以我将它包装在一个对象中来处理回调。
-
我的例子有点简化,因为它是 Redux reducer 和 Middleware 的一部分