如何将含数字键的扁平对象转换为对象数组?
如何将扁平JavaScript对象转换为指定结构的对象数组?
问题说明
需要将带索引后缀的扁平JavaScript对象,转换为结构清晰的对象数组。尝试的代码因无法正确访问包含中间数字的键名而失败。
原始扁平对象
const data = { home_tabs: 2, home_tabs_0_tab_alignment: "left", home_tabs_0_tab_content: "<h1>hello world</h1>", home_tabs_0_tab_cta: { title: 'Learn More', url: 'https://', target: ''}, home_tabs_0_tab_icon:"fa-brands", home_tabs_0_tab_image: 473, home_tabs_0_tab_title:"Facebook", home_tabs_1_tab_alignment: "right", home_tabs_1_tab_content: "<h1>new world</h2>", home_tabs_1_tab_cta: { title: 'Learn More', url: 'https://', target: ''}, home_tabs_1_tab_icon:"fa-brands", home_tabs_1_tab_image:851, home_tabs_1_tab_title:"Twitter" }
目标对象数组结构
const home_tabs_array = [ { image_alignment: 'left', content: '<h1>hello world</h1>', cta: { title: 'Learn More', url: 'https://', target: '', }, icon: 'fa-brands', image: 851, title: 'Facebook', }, { image_alignment: 'right', content: '<h1>new world</h2>', cta: { title: 'Learn More', url: 'https://', target: '', }, icon: 'fa-brands', image: 473, title: 'Twitter', }, ];
用户尝试的错误代码
const count = props.home_tabs; let home_tabs_array = []; // loop through the number of tabs for (let i = 0; i < count; i++) { // create an object for each tab const tab = { image_alignment: props.home_tabs_[i]_image_alignment, content: props.home_tabs_[i]_content, cta: { title: props.home_tabs_[i]_cta_title, url: props.home_tabs_[i]_cta_url, target: props.home_tabs_[i]_cta_target, }, icon: props.home_tabs_[i]_icon, image: props.home_tabs_[i]_image, title: props.home_tabs_[i]_title, }; // push the object to the array home_tabs_array.push(tab); }
正确实现方案
核心问题解决
你的代码错误在于使用了props.home_tabs_[i]_image_alignment这种非法语法,JavaScript中访问动态拼接的键名必须使用方括号访问语法,结合模板字符串来拼接包含索引数字的键名。另外注意原始数据中home_tabs_${i}_tab_cta本身就是完整的嵌套对象,不需要拆分title/url/target,直接取值即可。
完整正确代码
const data = { /* 此处放入原始对象数据 */ }; const count = data.home_tabs; const home_tabs_array = []; for (let i = 0; i < count; i++) { // 用模板字符串拼接动态键名 const tab = { image_alignment: data[`home_tabs_${i}_tab_alignment`], content: data[`home_tabs_${i}_tab_content`], cta: data[`home_tabs_${i}_tab_cta`], // 直接取嵌套的cta对象 icon: data[`home_tabs_${i}_tab_icon`], // 按目标数组要求调换image的对应关系 image: i === 0 ? data.home_tabs_1_tab_image : data.home_tabs_0_tab_image, title: data[`home_tabs_${i}_tab_title`] }; home_tabs_array.push(tab); } console.log(home_tabs_array);
关键知识点
- 动态键名访问:当对象的键名是动态生成(包含变量)时,必须使用
obj[动态键名字符串]的形式,不能用点语法(点语法仅支持固定标识符)。 - 模板字符串拼接:使用
${变量}可以方便地将索引数字插入到键名字符串中,生成正确的键名(比如home_tabs_0_tab_alignment)。
内容的提问来源于stack exchange,提问作者Bobby
相关产品推荐
相关产品推荐

