You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将对象数组的值分配到目标对象对应属性并设默认值为null?

实现对象数组到目标对象的属性映射(JavaScript)

需求说明

需要将包含url和country属性的对象数组,映射到键名规则为{country}_url的目标对象中,无对应值的属性统一设为null。

输入数据

const urlArrayOfObjects = [ 
    {url: 'https://amazon.co.uk', country: 'uk'},
    {url: 'https://amazon.com', country: 'usa'},
    {url: 'https://amazon.ca', country: 'canada'},
    {url: 'https://amazon.es', country: 'spain'}
];

目标对象模板

const urlTablesTemplate = {
    short_url_id: "",
    uk_url: "",
    usa_url: "",
    canada_url: "",
    irland_url: "",
    spain_url: "",
    germany_url: "",
    default_country: "",
    default_url: "",
    customer_id: ""
};

期望输出

const urlTables = {
    short_url_id: null,
    uk_url: "https://amazon.co.uk",
    usa_url: "https://amazon.com",
    canada_url: "https://amazon.ca",
    irland_url: null,
    spain_url: "https://amazon.es",
    germany_url: null,
    default_country: null,
    default_url: null,
    customer_id: null
};

实现方案

核心思路

  1. 先将输入数组转换为国家-URL映射表,实现快速查找
  2. 遍历目标对象模板的所有键,根据键名规则匹配映射表中的值,无匹配则设为null

完整代码

const urlArrayOfObjects = [ 
    {url: 'https://amazon.co.uk', country: 'uk'},
    {url: 'https://amazon.com', country: 'usa'},
    {url: 'https://amazon.ca', country: 'canada'},
    {url: 'https://amazon.es', country: 'spain'}
];

const urlTablesTemplate = {
    short_url_id: "",
    uk_url: "",
    usa_url: "",
    canada_url: "",
    irland_url: "",
    spain_url: "",
    germany_url: "",
    default_country: "",
    default_url: "",
    customer_id: ""
};

// 生成国家与URL的映射表
const countryUrlMap = urlArrayOfObjects.reduce((map, item) => {
    map[item.country] = item.url;
    return map;
}, {});

// 生成最终目标对象
const urlTables = Object.fromEntries(
    Object.entries(urlTablesTemplate).map(([key]) => {
        // 匹配{country}_url格式的键
        const countryMatch = key.match(/^(\w+)_url$/);
        if (countryMatch) {
            const country = countryMatch[1];
            // 有对应值则赋值,否则设为null
            return [key, countryUrlMap[country] ?? null];
        }
        // 非国家URL类的键直接设为null
        return [key, null];
    })
);

console.log(urlTables);

方案优势

  • 高效:时间复杂度为O(n + m)(n为数组长度,m为目标对象键数量),性能优异
  • 易扩展:后续新增国家或目标键时,无需修改核心逻辑
  • 可读性强:使用reduce、Object.fromEntries等现代JS API,代码逻辑清晰

内容的提问来源于stack exchange,提问作者SamNewbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 06:54:48