首页 > 解决方案 > 如何访问对象数组中的两个单独的图像并将其分配给同一数组中的第三个对象?

问题描述

我正在使用模拟数据来创建卡片组件,有些卡片有单个图像,而其他卡片有并排比较图像。我创建了一个上传数组,前两个对象有一个image,而对于第三个对象,我需要访问第一个和第二个对象中的图像以形成我的comparisons对象。我怎样才能做到这一点?我添加了一些有用的评论。

import faker from 'faker';
import uuid from 'uuid/v1';

const fakeUploads = [
    {
        avatar: faker.image.avatar(),
        description: faker.lorem.sentences(),
        id: uuid(),
        image: faker.image.avatar(),       
    },
    {
        avatar: faker.image.avatar(),
        description: faker.lorem.sentences(),
        id: uuid(),
        image: faker.image.avatar(),
        name: faker.name.findName(),        
    },
    {
        avatar: faker.image.avatar(),
        comparisons: { // Object.keys(comparison) => [0, 1]
            //Access to the two images in the above object where `0` is the index of the first image and `1` is the indes of the second

        },
        description: faker.lorem.sentences(),
        id: uuid(),
        name: faker.name.findName(),        
    },
];

我已经绘制了模拟上传的值,所以在我的组件中我想要类似的东西

values.includes(comparisons)? 
<span>
 <img width="50%" alt={UPLOAD} src={comparisons.image[0]} />
 <img width="50%" alt={UPLOAD} src={comparisons.image[1]} />
</span> : <img alt={UPLOAD} src={image} /> 

标签: javascriptreactjs

解决方案


您可以通过将第三个对象添加到范围内的数组来实现。

import faker from 'faker';
import uuid from 'uuid/v1';

const fakeUploads = [
    {
        avatar: faker.image.avatar(),
        description: faker.lorem.sentences(),
        id: uuid(),
        image: faker.image.avatar(),       
    },
    {
        avatar: faker.image.avatar(),
        description: faker.lorem.sentences(),
        id: uuid(),
        image: faker.image.avatar(),
        name: faker.name.findName(),        
    }
]

fakeUploads.push({
        avatar: faker.image.avatar(),
        comparisons: {[fakeUploads[0].image, fakeUploads[1].image]},
        description: faker.lorem.sentences(),
        id: uuid(),
        name: faker.name.findName(),
})

那是你要找的吗?


推荐阅读