需要从javascript中的对象数组中删除键中具有特定模式的特定对象

时间:2015-04-10 09:26:28

标签: javascript

您好我有以下类型的对象数组:

var person = [{
    "country" : "United States",
    "firstName/per/one" : "John",
    "lastName/per"  : "Doe",
    "age/per"       : 50,
    "eyeColo/per"  : "blue"
},{
    "firstName/per" : "james",
    "lastName.per"  : "bond",
    "age_per"       : 50,
    "eyeColo/per.xyz"  : "blue"
}];

我的要求是删除所有这些" key:value"密钥中包含任何斜杠(/)的对。因此,如果我们获取上面的对象数组,我所需的输出如下:

var person = [{
    "country" : "United States"    
},{
    "lastName.per"  : "bond",
    "age_per"       : 50    
}];

总之需要删除其键中具有特定模式的元素(上面的对象数组中的模式为" /")

由于

3 个答案:

答案 0 :(得分:3)

函数indexOf(pattern)将告诉您字符串是否包含所提供的模式。此外,在javascript中,您可以使用for循环迭代对象。因此,将它们结合在一起我们可以做到以下几点:


var person = [{
  "country": "United States",
  "firstName/per/one": "John",
  "lastName/per": "Doe",
  "age/per": 50,
  "eyeColo/per": "blue"
}, {
  "firstName/per": "james",
  "lastName.per": "bond",
  "age_per": 50,
  "eyeColo/per.xyz": "blue"
}];

var strippedPerson = [];
for (var i = 0; i < person.length; i++) {
  var newDetails = {};

  // iterate the keys of the person
  for (var key in person[i]) {
    // see if there is a slash in the key (indexOf returns -1 if there is no occurance of the pattern)
    if (key.indexOf('/') == -1) {
      // store the key and value as there is no slash
      newDetails[key] = person[i][key];
    }
  }
  strippedPerson.push(newDetails);
}
// strippedPerson has no keys with slashes in


document.write('<pre>person = ' + JSON.stringify(person, null, '\t') + '</pre>');
document.write('<pre>strippedPerson = ' + JSON.stringify(strippedPerson, null, '\t') + '</pre>');

答案 1 :(得分:1)

var person = [{
    "country" : "United States",
    "firstName/per/one" : "John",
    "lastName/per"  : "Doe",
    "age/per"       : 50,
    "eyeColo/per"  : "blue"
},{
    "firstName/per" : "james",
    "lastName.per"  : "bond",
    "age_per"       : 50,
    "eyeColo/per.xyz"  : "blue"
}];

for(var i = 0; i < person.length; i++) {
    for(key in person[i]) {
        if(key.indexOf('/')!=-1) {
            delete person[i][key]
        }
    }
}
console.log(person)

Fiddle Demo

答案 2 :(得分:0)

递归方法:

function removeSlash(arr){
var res={};
for(i in arr){
if(typeof arr[i]==='object'){res[i]=removeSlash(arr[i]);continue;}
if(i.indexOf('/')===-1)res[i]=arr[i]
}
return res;
}

var person = [{
"country" : "United States",
"firstName/per/one" : "John",
"lastName/per"  : "Doe",
"age/per"       : 50,
"eyeColo/per"  : "blue"
},{
"firstName/per" : "james",
"lastName.per"  : "bond",
"age_per"       : 50,
"eyeColo/per.xyz"  : "blue"
}];

person=removeSlash(person);
相关问题