嵌套映射reactjs

时间:2019-11-10 14:37:09

标签: javascript reactjs nested-map

我正在像下面那样在我的React应用程序中映射对象列表

(countrydata !== null) ? Object.keys(countrydata).map((item, key) => {
  return (
    <img src={countrydata[item].image_location}/>
  )
})

我还有一个数组,该数组具有与我上面映射的对象列表相同的确切对象数。我想显示数组对象中的某些数据,并且尝试执行类似的操作

(countrydata !== null) ? Object.keys(countrydata).map((item, key) => {
  arrayOfObjects.map((arrayItem,key)=>{
    return (
      <div>
        <img src={countrydata[item].image_location}/>
        <span>{arrayItem.name}</span>
      </div>
    )
  })            
})

但是无法达到我想要的结果。如何在对象列表映射中映射对象数组?

编辑:

我的对象列表如下(countrydata)

place_1:{description:'',image_location:'',location:''}
place_2:{description:'',image_location:'',location:''}
place_3:{description:'',image_location:'',location:''}

我的对象数组看起来像这样(arrayOfObjects)

0: {distance: {…}, duration: {…}, status: "OK"}
1: {distance: {…}, duration: {…}, status: "OK"}
2: {distance: {…}, duration: {…}, status: "OK"}

2 个答案:

答案 0 :(得分:0)

您不需要另一个嵌套的map。您可以仅使用一个map map同时使用它们,您将使用提供给回调的索引从另一个数组/对象访问该项。

顺便说一句,由于对象键的顺序不可靠,建议您在数组maparrayOfObjects,并使用索引生成键,以用于从{访问匹配的对象{1}}:

countrydata

答案 1 :(得分:0)

您可以合并两个数组并合并第二个数组中的值。

const data = {
place_1: { name: 'One'},
place_2: { name: 'Two'},
place_3: { name: 'Three'},
};

const countrydata = [];

const locations = [{distance: {}, duration: {}, status: "OK"},
{distance: {}, duration: {}, status: "OK"},
{distance: {}, duration: {}, status: "OK"}]

Object.keys(data).forEach((key, index) => countrydata.push({ [key]: { ...data[key], distance: locations[index].distance, duration: locations[index].duration }}))

console.log(countrydata);

然后像渲染数组一样

countrydata.map((item, key) => {
 return (
  <div>
    <img src={countrydata['place_' + key].image_location}/>
    <span>{countrydata['place_' + key].name}</span>
  </div>
 )
})