How is the specific object removed from the array

2020-07-23 04:23发布

I want to remove the 'hello5' from the years in myObj.

I used 'pop' prototype, but the browser console return this result :

'Uncaught TypeError: Cannot read property 'type' of undefined'

The following is an example for my issue. You could try and will see error message from console.

I tried a long time but I didn't find any solution, I need your advise and solution.

Code :

var myObj = {
  test : 'testObje',
  langs : {
    0 : 'EN',
    1 : 'GR',
    2 : 'RU',
    3 : 'TR'
  },
  comment : 'testComment'
};
var years = [];
  for (i= 0; i<=10; i++)
    {
      years.push({
        operator : i,
        type : 'hello' + i
      });
};
myObj.years = years;

var myObjLeng = myObj.years.length;
for(var i = 0; i < myObjLeng; i++) {
    if(myObj.years[i].type == 'hello5') {
        myObj.years.pop();
    }
}

5条回答
Root(大扎)
2楼-- · 2020-07-23 04:49

What about this one?

myObj.years = myObj.years.filter(year => year.type != "hello5")

in short you take myObj.years array an filter each of its elements called year in filiter callback. Filter will pass-thru these elements whose condition is met. All will met except ones with type with your"hello5" expression. Finally you substitute result back and you are done.

查看更多
神经病院院长
3楼-- · 2020-07-23 04:52

Your object key selection was wrong. Instead of for loop I suggest you to use map() function.

var myObj = {
        test : 'testObje',
        langs : {
            0 : 'EN',
            1 : 'GR',
            2 : 'RU',
            3 : 'TR'
        },
        comment : 'testComment'
    };
    var years = [];
    for (i= 0; i<=10; i++)
    {
        years.push({
            operator : i,
            type : 'hello' + i
        });
    };
    
    myObj.years = years;

    myObj.years.map((item, key) => {
        Object.keys(item).map(i => myObj.years[key][i] === 'hello5' && (delete myObj.years[key]))
    })

    console.log(myObj)

查看更多
我命由我不由天
4楼-- · 2020-07-23 05:00

pop will remove the last element, which will change the original array, that's why you are getting "Uncaught TypeError: Cannot read property 'type' of undefined" because after pop the index you are trying to access is not found on the array, instead use "array.filter"

let myObj =
  {
    test: 'testObje',
    langs: {0: 'EN',1: 'GR',2: 'RU',3: 'TR'},comment: 'testComment'
  };

let years = [];
for (let i = 0; i <= 10; i++) {
  years.push({ operator: i, type: 'hello' + i  });
};

myObj.years = years.filter(({type}) => type !== 'hello5')
查看更多
孤傲高冷的网名
5楼-- · 2020-07-23 05:04

There are some good alternatives here, so let me just take a stab at why you're getting that error.

You're getting that error because you're changing the length of the array mid-loop. At the beginning of the loop, you have 11 elements, and you use that to define how many times your for loop will go. When you get to hello5, you pop the last element off, making your array 10 elements long. However, your for loop will still try to access the 11th element. That will be undefined, and when you try to access a proprty of undefined (e.g. type), you will get a TypeError.

查看更多
太酷不给撩
6楼-- · 2020-07-23 05:13

pop always removes the last element, pop mutates original array, which affects index and you end up accessing indexs out of array length, you can simply use filter

let myObj = {test: 'testObje',langs: {0: 'EN',1: 'GR',2: 'RU',3: 'TR'},comment: 'testComment'};

let years = [];
for (let i = 0; i <= 10; i++) {
  years.push({ operator: i, type: 'hello' + i  });
};

myObj.years = years.filter(({type})=> type !== 'hello5')

console.log(myObj)

查看更多
登录 后发表回答