摘要:
我需要做类似的事情:
来自:
[ {
id: 1
content: "hello"
senderId: 1234
},
{
id : 2
content: "how are you"
senderId: 1234
},
]
到:
[
{
_id: 1,
text: 'hello',
user: {
_id: 1234,
},
},
{
_id: 2,
text: 'how are you',
user: {
_id: 1234,
},
},
]
说明:
我是javascript的新手(以及'新的'javascript用法,比如ES6)。我正在编写一个关于本机的应用程序。我正在使用mobx和firebase。
我有一个带有来自firebase的@oberservable消息的MessageStore。
import {observable, computed} from 'mobx';
import {Fb} from '../firebase/firebase';
import {map, toJS} from 'mobx';
import {Config} from '../config/config';
class Message{
id : string
content : string
senderId : string
}
class MessagesStore {
@observable messages = []
idConversation : string
constructor(idConversation) {
this.idConversation = idConversation
Fb.messages.child(idConversation).on('value', (snapshot) => {
value = snapshot.val();
let message = new Message()
message.id = value.id
message.content = value.content
message.senderId = value.senderId
this.messages.push(message)
});
}
@computed get allMessages(){
return this.messages
}
@computed get json() {
return toJS(this.messages);
}
}
...
问题是我想在UI中使用一个用于聊天的库(https://github.com/FaridSafi/react-native-gifted-chat) 国家必须是这样的:
this.setState({
messages: [
{
_id: 1,
text: 'Hello developer',
createdAt: new Date(),
user: {
_id: 2,
name: 'React Native',
avatar: 'https://facebook.github.io/react/img/logo_og.png',
},
},
],
})
)
我把这段代码放在:
messagesStore.messages.observe(() => ...
我的问题是:如何将我的消息数组(messagesStore.messages)映射到lib所需的数组。例如,我需要将消息属性内容映射到文本,或 id 映射到 _id
答案 0 :(得分:1)
我使用Array.map()
函数找到了解决方案:
var array1 = array2.map(function(obj){
var rObj = {};
rObj['_id'] = obj.id;
rObj['text'] = obj.content;
rObj['user'] = {};
rObj['user']['_id'] = obj.senderId;
return rObj;
})
编辑2:
使用ES6清理代码:
const array = array2.map(obj => {
const { id, content, senderId } = message;
return {
_id: id,
text: content,
user: {
_id: senderId
}
};
});