如何迭代不同的 variables/states 来创建一个对象?

How to iterate over different variables/states to create an object?

我需要帮助迭代 variables/state 个元素来创建一个对象。我将遍历 firstName 状态、lastName 状态以及更多状态。代码变得太复杂了。想知道是否有正确的方法来为 graphql 调用构建对象?或者只是构建对象的更好方法?

我有一个配置文件页面,其中包含用于更新用户帐户的表单。每个表单输入都有 state 和 setState 道具。在提交表单时,需要根据存储在状态中的帐户对象中存储的先前查询信息来检查这些值。我正在使用 graphql 端点,当我调用更新帐户调用时,我对 graphql 调用中的每个参数值有 3 个选择例如,firstName 可以是 1)Null(在数据库中删除) 2)一些非空值(在数据库中更改为该值) 3) 调用 graphql 调用中不存在字段(对该属性不做任何操作) 下面的代码我必须为 20 个不实用的状态值做。

// If there is a difference between client's firstName and queried firstName in server
if (firstName != account.firstName) {
  //If we stored firstName as empty String
  if(firstName === ''){ 
    //If the firstName queried is not empty
    if(account.firstName != null) {
      //Set the objects first name attribute to null, so server deletes field
      input['firstName'] = null;
    } else {
      //firstName is empty string and server value is null, so do nothing, do not add attribute firstName to object "input"
    }
  } else {
    //firstName is not an empty string so add it to object value
    input['firstName'] = firstName;
  }
}

如果有更好的方法来做到这一点,我很乐意提供帮助。

一种解决方法是使用括号表示法来提取指定要为其提取值的 key 以及需要检查的值。

function getComputedValue(value, key) {
  if (value != account[key]) {
    if (value === '') {
      if (account[key] != null) {
        input[key] = null;
      } else {
        
      }
    } else {
      input[key] = value;
    }
  }
}

let firstName = getComputedValue("Tom", "firstName");
let lastName = getComputedValue("Smith", "lastName");

有很多方法可以解决这个问题。我建议你使用Underscore JS提供的一些功能:

pairs_.pairs(object)

将对象转换为 [key, value] 对列表。对象的反义词。

_.pairs({one: 1, two: 2, three: 3});
=> [["one", 1], ["two", 2], ["three", 3]]

然后你可以遍历数组

_.each(array, function(pair) {
// Insert the input assignment code here for each key  
});