0

我正在映射我的反应应用程序中的对象列表,如下所示

(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>
    )
  })            
})

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

编辑:

我的对象列表如下所示(国家数据)

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"}
4

2 回答 2

0

You don't need another nested map. You can map them both at the same time using only one map, you'll use the index provided to the callback to access the item from the other array/object.

BTW, since the order of object keys is unreliable, I suggest you map over the array arrayOfObjects and use the index to generate the key that you'll use to access the matching object from countrydata:

arrayOfObjects.map((arrayItem, index) => {
  let key = "place_" + (index + 1);                      // generate the key to access an object from 'countrydata'. If we are at the first object (index == 0), the key will be "place_1"
  return (
    <div>
      <img src={countrydata[key].image_location}/>       // access the matching object from 'countrydata' and use it
      <span>{arrayItem.name}</span>                      // access the current array item from 'arrayOfObjects'
    </div>
  );
})
于 2019-11-10T14:39:37.057 回答
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>
 )
})        
于 2019-11-10T15:27:37.350 回答