gpt4 book ai didi

javascript - 将具有属性的数组映射到具有不同属性的数组

转载 作者:行者123 更新时间:2023-12-03 03:50:23 25 4
gpt4 key购买 nike

摘要:

我需要做类似的事情:

来自:

[  {
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 非常陌生(以及"new"javascript 用法,例如 ES6)。我正在用 React Native 编写一个应用程序。我正在将 mobx 与 firebase 结合使用。

我有一个 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 中使用一个库进行聊天 ( 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)映射到库所需的数组。例如,我需要将消息属性 content 映射到 text,或将 id 映射到 _id

最佳答案

我通过使用 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
}
};
});

关于javascript - 将具有属性的数组映射到具有不同属性的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45193056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com