检查字段属性是否存在,如果不从对象数组javascript中删除它

时间:2018-03-08 21:11:50

标签: javascript jquery arrays

我在javascript中有数组类型对象,我想检查字段属性是否存在,如果不从对象数组中删除它 例如,我拥有的数组是

var array = [{ 0:Common_Text_Area__c:"test 1"
  Evaluation__c:"a0W2F000000xB6sUAE"
  Id:"a0u2F000000ocv0QAA"
  Name:"ER-003346"
  Rating_Owner__c:"Employee"
  Review_Question__c:"a0w2F000000OoH5QAK"
1:Evaluation__c:"a0W2F000000xB6sSDE"
  Id:"a0u2F058254ocv0QAA"
  Name:"ER-013346"
  Rating_Owner__c:"Employee"
  Review_Question__c:"a0w2F000000OoH5QAK"}]

我想检查Common_Text_Area__c是否存在,如果它不存在然后将其全部删除所以我将在我的数组中结束这个

    var arrayTwo = [{ 0:Common_Text_Area__c:"test 1"
     Evaluation__c:"a0W2F000000xB6sUAE"
     Id:"a0u2F000000ocv0QAA"
     Name:"ER-003346"
     Rating_Owner__c:"Employee"
     Review_Question__c:"a0w2F000000OoH5QAK"}]

2 个答案:

答案 0 :(得分:2)

使用Array.prototype.filter返回一个只包含通过测试的元素的数组。使用in operator测试对象是否具有属性:

const result = arr.filter( obj => 'Common_Text_Area__c' in obj );

答案 1 :(得分:2)

功能filterincludes的替代方案。

var array = [{    'Common_Text_Area__c': "test 1",    'Evaluation__c': "a0W2F000000xB6sUAE",    Id: "a0u2F000000ocv0QAA",    Name: "ER-003346",    'Rating_Owner__c': "Employee",    'Review_Question__c': "a0w2F000000OoH5QAK"  },  {    'Evaluation__c': "a0W2F000000xB6sSDE",    Id: "a0u2F058254ocv0QAA",    Name: "ER-013346",    'Rating_Owner__c': "Employee",    'Review_Question__c': "a0w2F000000OoH5QAK"  }];

console.log(array.filter(o => Object.keys(o).includes('Common_Text_Area__c')));
.as-console-wrapper { max-height: 100% !important; top: 0; }

如果Common_Text_Area__c的值与undefinednull等不同,您可以使用解构分配。

var array = [{    'Common_Text_Area__c': "test 1",    'Evaluation__c': "a0W2F000000xB6sUAE",    Id: "a0u2F000000ocv0QAA",    Name: "ER-003346",    'Rating_Owner__c': "Employee",    'Review_Question__c': "a0w2F000000OoH5QAK"  },  {    'Evaluation__c': "a0W2F000000xB6sSDE",    Id: "a0u2F058254ocv0QAA",    Name: "ER-013346",    'Rating_Owner__c': "Employee",    'Review_Question__c': "a0w2F000000OoH5QAK"  }];

console.log(array.filter(({Common_Text_Area__c}) => Common_Text_Area__c));
.as-console-wrapper { max-height: 100% !important; top: 0; }