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

如何用Vanilla JavaScript更优获取嵌套数组中特定键值

优化Vanilla JavaScript获取JSON中customers的name值的实现

我正在学习Vanilla JavaScript,现有如下JSON对象:

{"createdBy":"System","createdDate":"2002-12-31T05:00:00.000+00:00","lastModifiedBy":"System","lastModifiedDate":"2023-12-31T05:00:00.000+00:00","id":2,"softwarename":"AcrobatReater","softwareprovider":"ADOBE","softwareprovidercontactemail":"admin@adobe.com","customers":[{"name":"CUSTOMER1","_links":{"softwares":[{"href":"http://localhost:8080/softwares/1"},{"href":"http://localhost:8080/softwares/2"}]}},{"name":"CUSTOMER2","_links":{"softwares":[{"href":"http://localhost:8080/softwares/1"},{"href":"http://localhost:8080/softwares/2"}]}}],"_links":{"self":{"href":"http://localhost:8080/softwares/2"},"appSoftware":{"href":"http://localhost:8080/softwares/2"}}}

目前我通过以下代码获取customers数组中每个元素的name值:

function custFunction(data.customers) {
            let htmlToSend = ''

            for (let i = 0; i < data.customers.length; i++) {
                const [key, val] = Object.entries(data.customers[i]);
                htmlToSend += `${key.toString().split(',')[1]}</br>`;
            }
            return htmlToSend;
        }

该实现方式不够严谨,若后续实体新增字段可能导致代码失效。请问是否存在更优的实现方案,尤其是函数式编程风格的方法,可精准获取目标键值?


问题分析

当前代码有两个核心问题:

  1. 依赖字段顺序:Object.entries()返回的键值对顺序由对象字段插入顺序决定,一旦给customer对象新增其他字段,第一个键值对就不再是name,直接取[key, val]会获取错误内容。
  2. 参数语法错误:函数参数写data.customers是无效语法,应改为接收customers数组或包含customers属性的data对象。

优化方案(函数式风格)

直接通过属性名精准访问name,结合数组map和join方法实现函数式写法,简洁且鲁棒:

基础版

function custFunction(customers) {
  // 提取每个customer的name,再用<br>拼接成字符串
  return customers.map(customer => customer.name).join('<br>');
}

// 调用示例
// const result = custFunction(data.customers);

增强鲁棒版(兼容异常场景)

如果需要处理customers非数组、部分customer无name属性的情况,可加入校验和可选链:

function custFunction(customers) {
  // 校验输入是否为数组,非数组直接返回空字符串
  if (!Array.isArray(customers)) return '';
  
  return customers
    .map(customer => customer?.name || '') // 可选链处理无name的情况,默认空字符串
    .filter(name => name) // 过滤空值,避免多余<br>
    .join('<br>');
}

方案优势

  • 精准可靠:直接访问name属性,不受对象其他字段增删、顺序变化的影响。
  • 函数式风格:用map(转换数组元素)和join(拼接字符串)替代手动循环,代码简洁易读。
  • 鲁棒性强:增强版加入输入校验和边界处理,避免运行报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 10:45:58