从json数组中删除记录

时间:2017-03-20 09:58:45

标签: javascript

我有一个json数组,格式如下:

Object {field: "l0", headerText: "0-22", width: 120}
Object {field: "l1", headerText: "23-43", width: 120}
Object {field: "l2", headerText: "44-55", width: 120}

我想根据headerText值删除记录

即。我有0-22的值,在此基础上我必须删除此记录。有可能吗?

4 个答案:

答案 0 :(得分:2)

假设您的对象包含在数组中,如下所示:

var arr = [
    {field: "l0", headerText: "0-22", width: 120},
    {field: "l1", headerText: "23-43", width: 120},
    {field: "l2", headerText: "44-55", width: 120}
]; 

您可以这样做:

var result = arr.filter(function(obj) {
    return obj.headerText !== "0-22"; // Or whatever value you want to use
});
console.log(result);

答案 1 :(得分:1)

Array.prototype.removeVal = function(name, value){
var array = $.map(this, function(v,i){
  return v[name] === value ? null : v;
});
this.length = 0; 
this.push.apply(this, array); //push all elements except the one we want to delete
}

var myArr = {};

myArray = [
{field: "l0", headerText: "0-22", width: 120},
{field: "l1", headerText: "0-11", width: 120},
{field: "l2", headerText: "0-33", width: 120}
];

myArray.removeVal('headerText', '0-11');

Fiddle

答案 2 :(得分:0)

for(var i = 0; i<jsonArray.length; i++){
    if(jsonArray[i]. headerText == "0-22"){
       jsonArray.splice(i, 1);
    }
}

答案 3 :(得分:0)

here

var objects = [
  {field: 'l0', headerText: '0-22', width: 120},
  {field: 'l1', headerText: '23-43', width: 120},
  {field: 'l2', headerText: '44-55', width: 120}
];

function filterObjects(element, index) {
  if (element.headerText === '0-22') {
    objects.splice(index, 1);
  }
}

objects.forEach(filterObjects);

console.log(objects);