gpt4 book ai didi

javascript - Normalizr - 这是一种为非 ID 实体模型生成 ID 的方法吗?

转载 作者:行者123 更新时间:2023-12-01 01:42:44 25 4
gpt4 key购买 nike

我正在使用 normalizr util 来处理基于非 ids 模型的 API 响应。据我所知,通常normalizr适用于ids模型,但也许有某种方法可以“随时随地”生成ids?

我的 API 响应示例:

```

// input data:
const inputData = {
doctors: [
{
name: Jon,
post: chief
},
{
name: Marta,
post: nurse
},
//....
}

// expected output data:
const outputData = {
entities: {
nameCards : {
uniqueID_0: { id: uniqueID_0, name: Jon, post: uniqueID_3 },
uniqueID_1: { id: uniqueID_1, name: Marta, post: uniqueID_4 }
},
positions: {
uniqueID_3: { id: uniqueID_3, post: chief },
uniqueID_4: { id: uniqueID_4, post: nurse }
}
},
result: uniqueID_0
}

```

附注我听说有人在 normalizr 中“通过引擎盖”生成 ID,以解决像我这样的情况,但我确实找到了这样的解决方案。

最佳答案

正如 issue 中提到的:

Normalizr is never going to be able to generate unique IDs for you. We don't do any memoization or anything internally, as that would be unnecessary for most people.

Your working solution is okay, but will fail if you receive one of these entities again later from another API endpoint.

My recommendation would be to find something that's constant and unique on your entities and use that as something to generate unique IDs from.

然后,正如文档中提到的,您需要设置 idAttribute 以将 'id' 替换为另一个键:

const data = { id_str: '123', url: 'https://twitter.com', user: { id_str: '456', name: 'Jimmy' } };

const user = new schema.Entity('users', {}, { idAttribute: 'id_str' });
const tweet = new schema.Entity('tweets', { user: user }, {
idAttribute: 'id_str',
// Apply everything from entityB over entityA, except for "favorites"
mergeStrategy: (entityA, entityB) => ({
...entityA,
...entityB,
favorites: entityA.favorites
}),
// Remove the URL field from the entity
processStrategy: (entity) => omit(entity, 'url')
});

const normalizedData = normalize(data, tweet);

编辑

您始终可以使用外部库或手动提供唯一的 ID:

inputData.doctors = inputData.doctors.map((doc, idx) => ({ 
...doc,
id: `doctor_${idx}`
}))

关于javascript - Normalizr - 这是一种为非 ID 实体模型生成 ID 的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52273858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com