如何将布尔数组值替换对象内users数组的checked属性,可使用Lodash实现
方案1:Lodash 实现
如果你的项目已经引入了Lodash,可以用下面的写法实现,提供两种可选逻辑:
// 写法1:不修改原对象,返回新的结果对象 const result = _.cloneDeep(object1); result.users = _.map(result.users, (user, index) => { // 若array1长度不足,保留原有checked值 return { ...user, checked: array1[index] ?? user.checked }; }); // 写法2:直接修改原对象,性能更高 _.forEach(object1.users, (user, index) => { if (index < array1.length) { user.checked = array1[index]; } });
方案2:原生JS实现
不需要依赖第三方库的纯原生写法,逻辑和Lodash版本一致:
// 写法1:不修改原对象,返回新的结果对象 const result = { ...object1, users: object1.users.map((user, index) => ({ ...user, checked: array1[index] ?? user.checked })) }; // 写法2:直接修改原对象 object1.users.forEach((user, index) => { if (index < array1.length) { user.checked = array1[index]; } });
如果可以确保array1的长度和object1.users的长度完全一致,可以去掉长度判断的逻辑进一步简化代码。
内容的提问来源于stack exchange,提问作者Code Junkie
相关产品推荐
相关产品推荐

