【问题标题】:map array based on another array data基于另一个数组数据映射数组
【发布时间】:2018-03-15 16:46:24
【问题描述】:

我有两个数组数据我只是想根据相同的 ID 获取数组 2 的数据 例子

import React from 'react';

const data = [
  {
    "userId": 1,
    "id": 1,
    "title": "One",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "Two",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
]
const dataTwo = [
  {
    "id": 1,
    "color": "red"
  },
  {
    "id": 2,
    "color": "blue"
  },
]
class App extends React.Component {

  render() {
    return (
      <div>
     {data.map((tweet)=> 
    <ul key={tweet.id}>
            <li>{tweet.title} <b>Color:</b> I want to put the color here</li>
     </ul>
     )}
      </div>
    );
  }
}
export default App;

如果 dataTwo 的 id === 数据的 id 所以我想获取相同项目的颜色

【问题讨论】:

  • @T.J.Crowder 抱歉,我已经搜索了一段时间,但找不到合适的解决方案,也许我找到了一些东西,但我不认识它,因为我只是初学者

标签: javascript reactjs


【解决方案1】:

你可以使用Array.prototype.find:

{data.map((tweet)=> {
    const { color = "default-color" } = dataTwo.find(item => item.id === tweet.id) || {};
    return <ul key={tweet.id}>
            <li>{tweet.title} <b>Color:</b> { color }</li>
     </ul>
})}

或者您可以更改dataTwo,使其成为一个对象(地图):

const dataTwo = {
    1: "red"
    2: "blue"
  };

然后直接访问:

{data.map((tweet)=>
     <ul key={tweet.id}>
            <li>{tweet.title} <b>Color:</b> { dataTwo[tweet.id] || 'default-color' }</li>
     </ul>
)}

【讨论】:

  • 非常感谢您的回答,我是 ReactJS 的新手,我尝试了代码它无法正常工作,没有控制台错误 codesandbox.io/s/p3n63oo2lx
  • @Lauradelgado 对此感到抱歉,我在更改 map 的箭头功能时忘记了 return。我已经更新了:)
【解决方案2】:

创建一个 dataTwo 对象,其中 key 为 id,value 为 color。循环时使用此对象获取颜色

var dataTwoObj = {};
dataTwo.reduce((data)=>{
    dataTwoObj[data.id] = data.color;
});
data.map((tweet)=> {
    const color = dataTwoObj[item.id];
    <ul key={tweet.id}>
            <li>{tweet.title} <b>Color:</b> { color }</li>
     </ul>
     )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 2017-05-26
    • 1970-01-01
    • 2014-07-03
    • 2022-09-27
    • 1970-01-01
    相关资源
    最近更新 更多