规范化链接的ID

时间:2017-10-06 04:07:05

标签: normalizr

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

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

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

1 个答案:

答案 0 :(得分:1)

我不确定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