需要帮助来更新对象中的值

need help to update the values in an object

我正在努力为这项任务编写代码。 这是我完成的代码 returns 一个对象,但我不知道如何根据需要更新对象。

function updateObj(obj,keyName,val) {
    obj = {};  
    keyName = this.keyName;
    val = this.val;
   
    if (val === obj.val) {
        val;
    } else {
        obj.val;
    }
   obj = {
       keyName: keyName,
       val
   };
   return obj;
}

下面是结果。

const bag = {
    color: 'yellow',
    hasMoney: false
}
updateObj(wallet, 'color', 'Blue'); => { color: 'Blue', hasMoney: false }

const house = {
    sqFt: 1500,
    isOccupied: true
}
updateObj(house, 'sqFt', 2000); // => { sqFt: 2000, isOccupied: true }

const cat = { isFurry: false };
const propName = 'isFurry';

cat['propName'] = true;
console.log(cat); // => { isFurry: false, propName: true }

看来您把问题复杂化了。可以简单到

function updateObj(obj,keyName,val) {
   obj[keyName] = val;
   return obj;
}

const bag = {
    color: 'yellow',
    hasMoney: false
}
console.log(updateObj(bag, 'color', 'Blue')); // => { color: 'Blue', hasMoney: false }

const house = {
    sqFt: 1500,
    isOccupied: true
}
console.log(updateObj(house, 'sqFt', 2000)); // => { sqFt: 2000, isOccupied: true }

const cat = { isFurry: false };
const propName = 'isFurry';

cat['propName'] = true;
console.log(cat); // => { isFurry: false, propName: true }

updateObj修改输入对象,设置一个属性。最后它 return 是对输入对象的引用。如果不需要 return 语句可以丢弃

function updateObj(obj,keyName,val) {
   obj[keyName] = val;
}

const bag = {
    color: 'yellow',
    hasMoney: false
}
updateObj(bag, 'color', 'Blue');
console.log(bag); // => { color: 'Blue', hasMoney: false }

const house = {
    sqFt: 1500,
    isOccupied: true
}
updateObj(house, 'sqFt', 2000);
console.log(house); // => { sqFt: 2000, isOccupied: true }

const cat = { isFurry: false };
const propName = 'isFurry';

cat['propName'] = true;
console.log(cat); // => { isFurry: false, propName: true }

使用展开运算符创建浅拷贝更简单

function updateObj(obj,keyName,val) {
   return { ...obj, [keyName]: val };
}

const bag = {
    color: 'yellow',
    hasMoney: false
}
console.log(updateObj(bag, 'color', 'Blue')); // => { color: 'Blue', hasMoney: false }

const house = {
    sqFt: 1500,
    isOccupied: true
}
console.log(updateObj(house, 'sqFt', 2000)); // => { sqFt: 2000, isOccupied: true }

const cat = { isFurry: false };
const propName = 'isFurry';

cat['propName'] = true;
console.log(cat); // => { isFurry: false, propName: true }

但在那种情况下,函数名称可能会造成混淆,因为输入对象未更新。

function updateObj(obj, keyName, val) {
  if (obj) {
      if (obj[keyName] != undefined){
        obj[keyName] = val;
      }
      return obj;
  }
}

const bag = {
    color: 'yellow',
    hasMoney: false
}
console.log(updateObj(bag, 'color', 'Blue'));
//console.log(updateObj(null, 'color', 'Blue'));
//console.log(updateObj(bag, 'food', 'Blue'));
const house = {
    sqFt: 1500,
    isOccupied: true
}
console.log(updateObj(house, 'sqFt', 2000));

您应该检查对象不为 null 并且对象具有该键,否则可能会 return 意外结果。