对象和数组的遍历
实现以下效果:对象中key有默认值,现在实现对象的key和数组元素如何能对应上,对象中obj[k] 变为true,否则变为false。
//方法一:保持原有obj[k] 的值
const arr = ["a", "b"];
const obj = {
a: "true",
b: "true",
c: "true",
d: "false",
};
const tmpObj = {};
arr.forEach((v) => (tmpObj[v] = true));
Object.assign(obj, tmpObj);
console.log("obj: ", obj);
//方法二:不保持原有obj[k] 值
const arr = ["a", "b"];
const obj = {
a: "true",
b: "true",
c: "true",
d: "false",
};
Object.keys(obj).forEach((k) => (obj[k] = arr.includes(k)));
console.log("obj: ", obj);
//(笨办法不推荐。。。)
// let arr = ['a','b'];
// let obj = {
// a:true,
// b:true,
// c:true,
// d:true,
// e:false,
// f:false
// }
// arr.forEach(itemKey =>{
// obj[itemKey] = true
// })
// let newArr = Object.keys(obj).filter(objKey=>{
// return !arr.includes(objKey);
// })
// newArr.forEach(item =>{
// obj[item] = false
// })
// console.log(obj);