let a={name:'111',age:222} 如果b是空对象,a中的属性都是空,如果b中的属性是空,a中的属性是空

发布时间 2023-12-20 10:14:59作者: 崛起崛起
let a = { name: '111', age: 222 };
let b = {};

// Iterate over the properties of a
for (let prop in a) {
  if (a.hasOwnProperty(prop)) {
    // Assign an empty string to the property in a
    a[prop] = '';
  }
}

console.log(a);
{name: '', age: ''}
let a = { name: '111', age: 222 };
let b = {};

// Iterate over the keys of a
Object.keys(a).forEach((key) => {
  // Assign an empty string to the property in a
  a[key] = '';
});

console.log(a);
{name: '', age: ''}
//用例
let a = { name: '111', age: 222 };
let b = {name:'333'}; // or any object with properties

// Iterate over the properties of a
for (let key in a) {
  if (a.hasOwnProperty(key)) {
    // If the property exists in b, use its value; otherwise, use an empty string
    a[key] = b[key] !== undefined ? b[key] : '';
  }
}

console.log(a);
{name: '333', age: ''}