代码之家  ›  专栏  ›  技术社区  ›  Xero

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

  •  0
  • Xero  · 技术社区  · 8 年前

    我需要这样做:

    发件人:

    [  {
          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)非常陌生。我正在react native上写一个应用程序。我在firebase上使用mobx。

    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所需的数组。例如,我需要映射消息属性 文本 身份证件

    1 回复  |  直到 8 年前
        1
  •  1
  •   Xero    8 年前

    我通过使用 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:

    const array = array2.map(obj => { 
      const { id, content, senderId } = message; 
      return { 
        _id: id, 
        text: content, 
        user: { 
          _id: senderId
        } 
      }; 
    });