【问题标题】:Is there a way of getting the value and setting it, of an element in the provided associative array有没有办法获取并设置提供的关联数组中元素的值
【发布时间】:2019-09-17 21:50:34
【问题描述】:

我有一个序列化模型,它是一个对象数组(关联?),我需要在其中获取和设置特定字段。

我尝试过使用 jQuery 和 js 进行迭代,但取得了一些有限的成功,但只能获得 1 级键。

{
  "Branch": {
    "ID": 123,
    "Code": "xyz",
    "FkRegionID": null,
    "FkEntityPersonID": null,
    "ParentID": null,
    "Detail": null,
    "Addresses": [],
    "TelephoneNumbers": [],
    "DeletedTelephoneNumbers": [],
    "BankAccounts": [],
  },

  "ParentLookup": null,

  "Address": {
    "ID": 55,
    "FkEntityPersonID": 27,
    "FkEntityAddressTypeID": 1,
    "Address1": null,
    "Address2": null,
    "Address3": null,
    "Address4": null,
    "FkCityID": null,
    "PostalCode": null,
    "CountryID": null,
    "RegionID": null,
    "AddressTypeDetail": null,
    "CityDetail": null
  },

  "AddressCityLookup": null,

  "Telephone": {
    "ID": null,
    "FkEntityPersonID": 27,
    "FkTelephoneTypeID": 1,
    "TelephoneNumber": 0826559999,
    "TelephoneTypeDetail": null
  },
  "TelephoneTypeLookup": null,

}

我想获取任何键值对的值并进行设置。例如获取 ID=123 的 'BranchCode' 和 'code' 并设置 'Code' 字段。

编辑: 这行得通。 下一步是将其提取到它自己的数组中,但这是一个不同的问题。

   $.each(serializedObject, function (key, value)
    {
        console.log("key= " + key + "   ." + value);
        if (key == 'Branch')
        {
            value.ID = 456;

            // Get this into a standalone array?
            // newArray
        }
    });

谢谢

【问题讨论】:

  • 您尝试获取或设置对象的键是什么?您面临什么问题?

标签: javascript associative-array key-value


【解决方案1】:

您可以使用 Array.prototype.find (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) 方法找到您需要的确切元素,然后您可以对其进行修改。即

const yourArray = [...];

const targetElement = yourArray.find(function(el){ 
  return el.Branch.ID === '123';
});
targetElement.Branch.code = 'new code';

但是,如果您的目标是较旧的浏览器,您将需要一个 polyfill。根据 MDN:

// https://tc39.github.io/ecma262/#sec-array.prototype.find
if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, 'find', {
    value: function(predicate) {
     // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
      if (typeof predicate !== 'function') {
        throw new TypeError('predicate must be a function');
      }

      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
      var thisArg = arguments[1];

      // 5. Let k be 0.
      var k = 0;

      // 6. Repeat, while k < len
      while (k < len) {
        // a. Let Pk be ! ToString(k).
        // b. Let kValue be ? Get(O, Pk).
        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
        // d. If testResult is true, return kValue.
        var kValue = o[k];
        if (predicate.call(thisArg, kValue, k, o)) {
          return kValue;
        }
        // e. Increase k by 1.
        k++;
      }

      // 7. Return undefined.
      return undefined;
    },
    configurable: true,
    writable: true
  });
}

【讨论】:

  • 不幸的是,使用 '=>' 会导致语法错误。我正在使用 IE 11。
  • 我已更新答案以添加 IE 11 支持。此外,polyfill 由 MDN 提供。
  • 我收到一个 js 错误。对象不支持“查找”属性或方法
  • 这就是为什么您需要在调用第一位之前包含代码的第二位(polyfill)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-18
  • 2018-02-23
  • 1970-01-01
  • 2012-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多