如何在函数参数javascript中指定对象位置

时间:2017-05-28 05:36:55

标签: javascript

我希望能够使用一个函数更新一个Object或几个对象,该函数指定我想要在Obeject中更新的位置。我不确定它的正确语法是什么。我下面的尝试实际上在原始对象中创建了一个新参数,而我想要更新User对象的现有字段。

var User = {
    local: {
    location: {
      city: "",
      state: ""
    }
  }
}

var Profile = {
    location: {
    city: "",
    state: ""
    }
}

function update(model, parameter, updatedLocation)  {
        return model[updatedLocation] = {
        city: updatedLocation.city,
      state: updatedLocation.state,
    };
}

update(User, ["local"]["location"], { city: "ny", state: "ny"});
update(Profile, ["location"], { city: "ny", state: "ny"});

console.log(User);
console.log(Profile);

JS Fiddle

2 个答案:

答案 0 :(得分:1)

你可以尝试一下。基本上,它是进入对象中任何级别并更新属性的通用方法。代码注释中的详细信息



var User = {
  local: {
    location: {
      city: "",
      state: ""
    }
  }
}

var Profile = {
  location: {
    city: "",
    state: ""
  }
}

function update(obj, path, updatedProps) {
  var objToUpdate = obj;
  // Iterate down the path to find the required object
  for (var i = 0; i < path.length; i++) {
    if (objToUpdate[path[i]]) {
      objToUpdate = objToUpdate[path[i]]
    } else {
      // If any path is not found, then no point continuing
      objToUpdate = null;
      break;
    }
  }
  if (objToUpdate) {
    var props = Object.keys(updatedProps);
    for (var j = 0; j < props.length; j++) {
      var prop = props[j];
      objToUpdate[prop] = updatedProps[prop] || objToUpdate[prop];
    }
  }
  return obj;
}

update(User, ["local", "location"], {
  city: "ny",
  state: "ny"
});
update(Profile, ["location"], {
  city: "ny",
  state: "ny"
});

console.log("User:", User);
console.log("Profile:", Profile);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

与此处的其他答案类似,但它不需要location结构的显式编码:

function update(model, parameter, newVal) {
    model[parameter] = newVal;
}

update(User["local"], "location", { city: "ny", state: "ny"});
update(Profile, "location", { city: "ny", state: "ny"});

或者,如果您只是更新位置,则可以简化功能:

function updateLocation(model, newVal) {
    model.location = newVal;
}