如何从对象中删除键
此函数采用一组用户对象,并删除每个用户对象上的moto键值对。 例如。
[
{name: 'Mike', moto: 'ilovetea'},
{name: 'Sandy', moto: 'ilovecoffee'},
{name: 'Sandra', moto: 'ilovepie'}
]
返回:
[
{name: 'Mike' },
{name: 'Sandy'},
{name: 'Sandra'}
]
我尝试了以下代码:
function deleteAllMoto(users) {
for(var i=0; i<=users.length; i++) {
delete users[i].password;
return users[i];
}
针对此代码:
describe('deleteAllMoto', function() {
it('deletes the moto key value pair on every object in an array of createUserString', function() {
expect(
deleteAllMoto([
{name: 'Mike', moto: 'ilovetea'},
{name: 'Sandy', moto: 'ilovecoffee'},
{name: 'Sandra', moto: 'ilovepie'}
])
).to.eql([{ name: 'Mike' }, { name: 'Sandy' }, { name: 'Sandra' }]);
expect(
deleteAllMoto([
{ name: 'Simon', moto: 'ilovetea' },
{ name: 'Libara', moto: 'ilovepie' }
])
).to.eql([{ name: 'Simon' }, { name: 'Libara' }]);
});
});
答案 0 :(得分:1)
类似这样的东西:
function deleteAllMoto (arr) {
arr.forEach(function(item) {
delete item.moto
})
return arr
}
从您的代码中删除的密码不是moto,然后尝试在突变后返回每个用户而不是整个数组。
答案 1 :(得分:0)
deleteAllMoto
函数应该是
function deleteAllMoto(users) {
for(var i=0; i<=users.length; i++) {
delete users[i].moto;
}
return users;
}