Javascript 将具有属性的数组映射到具有不同属性的数组
摘要: 我需要这样做:Javascript 将具有属性的数组映射到具有不同属性的数组,javascript,reactjs,react-native,mobx,mobx-react,Javascript,Reactjs,React Native,Mobx,Mobx React,摘要: 我需要这样做: this.setState({ messages: [ { _id: 1, text: 'Hello developer', createdAt: new Date(), user: { _id: 2, name: 'React Native',
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',
},
},
],
})
)
发件人:
[ {
id: 1
content: "hello"
senderId: 1234
},
{
id : 2
content: "how are you"
senderId: 1234
},
]
致:
说明:
我对javascript(以及“新的”javascript用法,如ES6)非常陌生。我正在用react native编写一个应用程序。我在用mobx和firebase
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);
}
}
...
我有一个MessageStore,里面有来自firebase的@oberservable消息数组
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中使用一个用于聊天的库()
国家必须是这样的:
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我使用以下函数找到了解决方案:
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
}
};
});