更新 JavaScript 对象时,提供什么值以保持值相同

When update a JavaScript object, what value to provide to keep the value to be the same

这是我的程序:

let existingData = {
    name: 'David',
    age: 32,
    isSingle: true,
    country: 'United States'
};

let input = {
    name: 'Mike',
    age: null, // The question is how to keep age value to be 32
    isSingle: false,
    country: 'France'
};

existingData['name'] = input['name'];
existingData['age'] = input['age'];
existingData['isSingle'] = input['isSingle'];
existingData['country'] = input['country'];

console.log(existingData);

当我运行它时,这是我看到的:

{
    name: 'Mike',
    age: null,
    isSingle: false,
    country: 'France'
}

这是我所期望的:

{
    name: 'Mike',
    age: 32,
    isSingle: false,
    country: 'France'
}

所以我的问题是我应该为输入年龄提供什么值以保持值 32。 我试过 null 但它不起作用。

有什么办法可以解决这个问题吗?

您可以使用条件运算符(如三元运算符)来检查 input 中的值是否为空。如果它是 null 它将分配 existingData 的值,如果不是 null,它将分配 input 对象值。

let existingData = {
    name: 'David',
    age: 32,
    isSingle: true,
    country: 'United States'
};

let input = {
    name: 'Mike',
    age: null, // The question is how to keep age value to be 32
    isSingle: false,
    country: 'France'
};

existingData['name'] = input['name'];
existingData['age'] = input['age'] === null ? existingData['age'] : input['age'];
existingData['isSingle'] = input['isSingle'];
existingData['country'] = input['country'];

console.log(existingData);

对于一般情况,您可以使用.filterObject.entries过滤掉空值,然后使用Object.assign:

let existingData = {
    name: 'David',
    age: 32,
    isSingle: true,
    country: 'United States'
};

let input = {
    name: 'Mike',
    age: null, // The question is how to keep age value to be 32
    isSingle: false,
    country: 'France'
};

Object.assign(
  existingData,
  Object.fromEntries(
    Object.entries(input).filter(([, val]) => val !== null)
  )
);
console.log(existingData);