简体   繁体   中英

How can I access two separate images in an array of objects and assign it to a third object inside the same array?

I am using a mock data to create a card component, some cards have single image while others have side by side comparison images. I have created an array of uploads, the first two objects have an image , while for the third object, I need to get access to the image in the first and second object to form my comparisons object. How can I achieve that? I added some helpful comments.

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(),        
    },
];

I have already mapped out the values of the mock upload, so in my component I want to have something like

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

You could do it by adding the third object to the array in scope.

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

Is that what you're looking for?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM