如何将字典数组中的country字段值拼接为指定格式字符串?
解决方案
你可以通过 map() 方法先提取数组中每个对象的 country 属性,将原数组转换为纯国家名的数组,再使用 join('-') 完成拼接:
代码示例
// 原数据 const a = [{"country":"Colombia","date":"1995"}, {"country":"China","date":"1995"},{"country":"USA","date":"1992"}]; // 转换并拼接 const countryStr = a.map(item => item.country).join('-'); console.log(countryStr); // 输出:"Colombia-China-USA"
补充说明
如果数组中存在缺失 country 属性的对象,可以添加容错处理,避免出现 undefined:
const countryStr = a.map(item => item?.country || '').join('-');
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

