简体   繁体   English

jQuery检查索引值的一部分

[英]jQuery check for part of Index value

I have an array or objects and I need to find a key that contains part of a string, not the value associated with the key. 我有一个数组或对象,我需要找到一个包含字符串一部分而不是与该键关联的值的键。 Can inArray do this or is there an alternative? inArray可以执行此操作吗?还是有替代方法?

Example array has a key with form_iQc2lz6yr7[contactName] and a value of "John Smith". 示例数组的键为form_iQc2lz6yr7[contactName] ,值为“ John Smith”。 I need to search in this array for the key containing the string "[contactName]" as the string before this can change but [contactName] will always stay the same. 我需要在此数组中搜索包含字符串“ [contactName]”的键,因为它可以更改之前的字符串,但是[contactName]将始终保持不变。 Then I need to change the key to just "contactName". 然后,我需要将密钥更改为“ contactName”。

Example: 例:

[
  {name: "action", value: "someUrl"},
  {name: "list", value: "123344"},
  {name: "form_iSfMSWen3Y[contactName]", value: ""},
  {name: "form_iSfMSWen3Y[email]", value: ""},
  {name: "form_iSfMSWen3Y[subject]", value: ""}
]

Full context, I need to submit this form via ajax then once that is complete, change the key of form_iSfMSWen3Y[contactName], form_iSfMSWen3Y[email], and form_iSfMSWen3Y[subject] to contactName, email, subject, respectively and then submit to another url. 完整的上下文,我需要通过ajax提交此表单,然后在完成后,将form_iSfMSWen3Y [contactName],form_iSfMSWen3Y [email]和form_iSfMSWen3Y [subject]的密钥分别更改为contactName,电子邮件,主题,然后提交给另一个URL 。

you can do this in one .map() 您可以在一个.map()完成此操作

obj = {
  p1_abc: 1,
  p2_abc: 2,
  p3_def: 3,
  p4_abc: 4,
  p5_def: 5
}

required_keys = jQuery.map(Object.keys(obj), function(val, i) {
  if (val.indexOf("_abc") != -1) {
    return obj[val];
  }

});
document.write(required_keys);

or If you want key/values you can do like 或者,如果您想要键/值,可以这样做

obj = {
  p1_abc: 1,
  p2_abc: 2,
  p3_def: 3,
  p4_abc: 4,
  p5_def: 5
}

required_keys = jQuery.map(Object.keys(obj), function(val, i) {
  if (val.indexOf("_abc") != -1) {
    return {[val]:obj[val]};
  }

});
document.write(JSON.stringify(required_keys));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM