如何将数组内对象的自身所属索引作为该对象指定属性的值?
对象字面量声明阶段还未被加入数组,无法直接获取自身在数组中的索引,可通过以下几种方式实现需求:
方案1:初始化数组时批量生成带索引的对象
// 先定义不带id的基础数据 const baseData = [ { "color": "purple", "type": "minivan" }, { "color": "red", "type": "station wagon" } ] // 利用Array.from的映射回调生成带索引id的数组 const array_of_objects = Array.from(baseData, (item, index) => ({ ...item, id: index }))
方案2:已有数组批量补充id属性
如果数组已经定义完成,直接遍历赋值即可:
let array_of_objects = [ { "color": "purple", "type": "minivan" }, { "color": "red", "type": "station wagon" } ] // forEach回调的第二个参数就是当前项的索引 array_of_objects.forEach((item, index) => { item.id = index })
方案3:渲染表单时直接取遍历索引(无需存储id)
如果仅需要在表单输入项展示索引,不需要把索引持久保存在对象中,遍历渲染时直接用遍历提供的索引参数即可,原生JS示例:
const formWrap = document.querySelector('#form-wrap') array_of_objects.forEach((item, index) => { formWrap.innerHTML += ` <div class="form-item"> <label>当前索引:</label> <input value="${index}" readonly /> <label>车辆颜色:</label> <input value="${item.color}" /> <label>车辆类型:</label> <input value="${item.type}" /> </div> ` })
内容的提问来源于stack exchange,提问作者Vaggelis
相关产品推荐
相关产品推荐

