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

如何映射两个对象的数据并从其中提取细节?

  •  0
  • Pranav  · 技术社区  · 5 年前

    在我的一个项目中,我需要按如下方式映射两个对象:

    const artistData = [
    {
       "_id":"abc123",
       "name":"John Sams",
       "age" : 35
    },
    {
       "_id":"pqr123",
       "name":"John Adams",
       "age" : 45
    },
    {
       "_id":"abc455",
       "name":"Patrick",
       "age" : 39
    },
    {
       "_id":"xyz345",
       "name":"Matt Hardy",
       "age" : 43
    }
    
    ]
    
    const messageData = [
    {
    "artistId": "xyz345",
    "message": "Hello Matt!!!"
    }
    ]
    

    在这里,我想映射“artistData”的artist_id和“messageData”的artistId,以便从第一个对象数组中提取数据。我使用了以下方法:

    artistData.some(artistId => artistId._id === messageData.artistId)
    

    最好的解决方案是什么?

    0 回复  |  直到 5 年前
        1
  •  2
  •   Dakota Lee Martinez    5 年前

    你被要求满足的确切要求是什么?您是否正在尝试获取属于特定艺术家的所有消息?根据你到底想做什么,答案会有所不同。

    例如,如果你从一位艺术家开始 someArtist 如果你想把所有的消息都发送给他们,你可以这样做:

    messageData.filter(message => message.artistId === someArtist._id)
    

    如果你从一条消息开始 someMessage 如果你想把它发给艺术家,你可以做这样的事情:

    artistData.find(artist => artist._id === someMessage.artistId)
    

    编辑

    如果你想在消息中添加艺术家的名字,你可以这样做:

    const messageWithArtistName = {
      ...someMessage, 
      name: artistData.find(artist => artist._id === someMessage.artistId).name}
    }
    

    请注意,如果你找不到匹配的艺术家,这将失败

    再次编辑

    如果你想这样做,所有的消息。

    messageData.map(message => {...message, name: artistData.find(artist => artist._id === message.artistId).name })
    
        2
  •  0
  •   pheianox    5 年前

    更好的方法是反其道而行之。

    让我们首先循环查看消息 .forEach() 对于每一条信息,我们都会使用 .find() 数组方法

    const artists = [
    { id: "19823908109", name: "Johnas Smith", age: 44 },
    { id: "00823933109", name: "Jane Doe",     age: 19 },
    { id: "30823908109", name: "Mary Air",     age: 20 },
    { id: "58239081091", name: "Tom Silver",   age: 87 },
    ];
    
    const messages = [
    { id: "58239081091", message: "Hello World" },
    { id: "30823908109", message: "Hi, Tom!" }
    ];
    
    
    
    // Loop through every single message
    messages.forEach( ({ id, message }) => {
    
      // Find the artist
      const artist = artists.find( artist => artist.id === id );
      
      // Log the artist
      console.log(artist)
    });