规范化链接 ID

Normalize linked ids

我这里有一组奇怪的数据。

const data = {
    profiles: [
        { name: 'Joe', photos: [1, 2, 3] },
        { name: 'Ryan', photos: [2] },
        { name: 'Bob', photos: null }
    ],
    linked: {
        photos: [
            { id: 1, url: 'http://blah' },
            { id: 2, url: 'blah' },
            { id: 3, url: 'asdf' }
        ]
    }
}

我得到的所有配置文件都是这样的:

const { entities } = normalize(data, {
    profiles: [ Profile ]
});

但是我想用 linked.photos 中的条目替换 photos id 数组,这可能吗?还是需要 post 处理?我目前正在进行自定义 post 处理。

我不确定 normalizr 是否是完成您的任务的最佳方法,但像这样的方法会起作用

const photoSchema = new schema.Entity('photos', {});
const normalized = normalize(data.linked.photos, [photoSchema]);
const profileRawSchema = new schema.Entity('profiles', {}, {idAttribute: 'name'})
const profileSchema = new schema.Entity('profiles', {
    photos: [photoSchema]
}, {idAttribute: 'name'});
const normalizedProfiles = normalize(
    data.profiles,
    [profileRawSchema]
);

normalized.entities.profiles = normalizedProfiles.entities.profiles;
// here is what you want
const desiredResult = denormalize(normalizedProfiles.result, [profileSchema], normalized.entities);

Docs for denormalize