如何在JavaScript中向数组内className为section的对象后插入新JSON对象
实现方案
方案1:使用reduce生成新数组(不修改原数组)
该方案不会改动原始数组,适合需要保留原数据的场景,逻辑简单不易出错:
const arr = [ {"className":"section", "name":"input"}, {"className":"col", "name":"dropdown"}, {"className":"section", "name":"table"} ]; const res = arr.reduce((acc, cur) => { acc.push(cur); // 匹配到className为section的对象时,插入指定新对象 if (cur.className === 'section') { acc.push({ fieldName: 'new' }); } return acc; }, []);
方案2:倒序遍历修改原数组
如果允许直接修改原始数组,可以用倒序遍历加splice插入,避免正序插入时索引偏移导致的匹配错误:
const arr = [ {"className":"section", "name":"input"}, {"className":"col", "name":"dropdown"}, {"className":"section", "name":"table"} ]; for (let i = arr.length - 1; i >= 0; i--) { if (arr[i].className === 'section') { // 在当前元素的后一位插入新对象 arr.splice(i + 1, 0, { fieldName: 'new' }); } }
两种方案最终输出的数组结构都和需求完全一致。
内容的提问来源于stack exchange,提问作者Yaditya
相关产品推荐
相关产品推荐

