我正在构建一个工具,允许用户从通用源(具有通用结构)中获取数据并重新映射属性以匹配我的API。
- 用户将输入源URL(REST API或JSON);
- 用户将输入基于JSON的DTO指令
DTO将是像这样的JSON:
{
"data.collection.name": "section.title",
"just.an.example": "data.foo",
}
当来源提供了具备此结构的数据时:
{
"data": {
"foo": "bar",
"collection": {
"totalCount": 123,
"title": "Best sellers",
}
}
}
该功能将重新映射该值为:
{
"section": {
"title": "Best sellers"
},
"just": {
"an": {
"example": "bar"
}
}
}
我可以使用lodash中的get
和set
方法来实现此操作,具体算法如下:
const data = {
foo: "bar",
collection: {
title: "BestSellers",
},
just: {
an: {
example: "bar",
},
},
nodes: {
edges: [
{
title: "Orange juice",
slug: "orange-juice",
},
{
title: "Apple juice",
slug: "apple-juice",
},
],
},
};
let transformed = {};
const transformer = {
"collection.title": "section.title",
"just.an.example": "foo",
};
Object.keys(transformer).forEach((key) => {
const value = _.get(data, key);
const path = transformer[key];
_.set(transformed, path, value);
});
console.log(transformed);
现在我需要使用数组属性(如nodes.edges
)来实现相同的结果。
User DTO JSON应该长成这个样子(不是必需的,但理想情况下):
{
"data.collection.name": "section.title",
"nodes.edges.title": "products.title",
"nodes.edges.slug": "products.seo.slug",
}
将生成以下输出:
{
"section": {
"title": "BestSellers"
},
"products": [
{
"title": "Orange Juice",
"seo": {
"slug": "orange-juice"
}
},
{
"title": "Apple Juice",
"seo": {
"slug": "apple-juice"
}
}
]
}
node.edges[].title
,表示此时你期望一个数组,并为其定义特定的处理方式 :) 这样做有益处,可以验证DTO与接收到的数据,以及能够读取数组属性和数组内对象属性(例如,他们想将nodes.edges.length
重新映射为products.count
) - Icepickle