无法从js对象中删除键值对

时间:2019-04-10 12:33:33

标签: javascript arrays node.js json mongodb

我从mongodb查询中收到一个js对象,我想使用delete optr从对象中删除一个键值对,但不删除,并且isFollowing值未设置,但是如果部分成功运行,则代码在其中。 (使用nodeJS)

我已经尝试使用delete optr进行删除。...但是它与undefined一起使用,但是我设置为isFollowing的值未反映在对象中。

baseData.numFollowers = baseData.followers.length;
    baseData.numFollowing = baseData.following.length;    
    if(forWhom === 'self'){
        delete baseData.following;
        delete baseData.followers;
    }else 
    if(forWhom === 'other'){
        const selfUID = req.body.self_id;
        baseData.isFollowing = baseData.followers.includes(selfUID);
        delete baseData.followers;
        delete baseData.following;

    }

    let toSend = {success:true, basic:baseData};

获得结果:

{ 
  following: [],
  followers: [],
  numFollowers: 0,
  numFollowing: 0
 }

预期结果:

{
  numFollowers: 0,
  numFollowing: 0,
  isFollowing: true (or false)
}

1 个答案:

答案 0 :(得分:2)

要使用delete,您需要通过调用toObject将模型文档转换为普通的JavaScript对象,以便您可以像这样自由地对其进行操作:

const base = baseData.toObject();

base.numFollowers = base.followers.length;
    base.numFollowing = base.following.length;    
    if(forWhom === 'self'){
        delete base.following;
        delete base.followers;
    }else 
    if(forWhom === 'other'){
        const selfUID = req.body.self_id;
        base.isFollowing = base.followers.includes(selfUID);
        delete base.followers;
        delete base.following;

    }

    let toSend = {success:true, basic:base};