嵌套映射reactjs



我正在我的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"}

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

顺便说一句,由于对象密钥的顺序不可靠,我建议您在数组arrayOfObjects上使用map,并使用索引生成密钥,您将使用该密钥从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>
);
})

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

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

最新更新