可以使用模板将值从一个对象映射到另一个具有不同结构的对象吗?

时间:2017-07-12 01:55:35

标签: javascript object

我的API响应看起来像这样:

const apiResponse = {
    entries: [
        {
            title: "Entry Title",
            url_title: "entry-title",
            status: "open",
            created_date: "14 Apr 2017",
            category: {
                cat_name: "Information",
                cat_url_title: "information"
            },
            channel_name: "Entries",
            content: {
                text_position: "textBottomRight",
                large_image: {
                    image: "https://placeimg.com/2732/752/nature/grayscale",
                    width: 2732,
                    height: 752
                },
                small_image: {
                    image: "https://placeimg.com/1500/716/nature/grayscale",
                    width: 1500,
                    height: 716
                },
                content: "A short summary goes *here*.",
                feature_theme: {
                    theme: "themePositive",
                    background_color: "rgb(27, 27, 36)",
                    eyebrow_color: "rgb(255, 255, 255)",
                    headline_color: "rgb(255, 255, 255)",
                    text_color: "rgb(255, 255, 255)",
                    link_color: "rgb(77, 175, 255)"
                },
                enable_favoriting: 0,
                related_article: "",
                continue_link_text: "",
                large_image_height: 0,
                large_image_width: 0,
                small_image_width: 0,
                small_image_height: 0
            },
            id: 614
        }, {
            … more entries
        }
    ]
};

此响应的键和结构会根据请求的“频道”略有不同。目前有三个不同的通道,每个通道只有一个略微不同的结构和一些可能不存在于其他响应中的不同键。无论数据源的结构如何,所有响应都需要在前端归结为相同的格式。

所以我想知道,当结构不同时,有推荐的方法将值从一个对象映射到另一个对象吗?

我最初的想法是为每个频道创建一个“模板”。类似的东西:

const channelOne = {
    entries: {
        title: 'entries.title',
        slug: 'entries.url_title',
        status: 'entries.status',
        date: 'entries.created_date',
        category: 'entries.category.cat_name',
        name: 'entries.channel_name',
        content: {
            format: 'entries.content.text_position',
            image: {
                large: 'entries.content.large_image.image',
                small: 'entries.content.small_image.image'
            }
        },
        … etc.
    }
};

我会为每个“频道”创建其中一个。然后,对于每个响应,我将使用此模板将响应中的值映射到此模板中的键。没有真正解决这个实际上如何工作,因此我晚上访问了SO。

有什么建议吗?

0 个答案:

没有答案