Nodejs:更改对象中的单个键值

时间:2017-07-04 07:41:53

标签: javascript node.js mongodb express

以前曾经问过,但我无法理解答案。所以我再问一次。这是我需要操纵的对象。

[ 
  "description": {
      "zh": "CDes",
      "en": "EDes"
  },
  "nutrition": {
      "zh": "CNutrition",
      "en": "ENutrition"
  },
  "brand_names": {
      "zh": "chineseBName",
      "en": "englishBName"
  }
]

当我使用以下原始代码

向网址发送put请求时
{ 
   description: {
     "zh" : "chinese"
   }
}

它变为

[
  "description": {
      "zh": "Chinese",

  },
  "nutrition": {
      "zh": "CNutrition",
      "en": "ENutrition"
  },
  "brand_names": {
      "zh": "chineseBName",
      "en": "englishBName"
  }
]

但我想保留“en”:“EDes”。我用$ set作为

if (req.body.description.zh !== "undefined"){
    const id = "{" + req.params + " }";
    var obj = {
        'zh' : req.body.description.zh
    };

    Product.update(id, {'$set': {
        "description.$.zh" : req.body.description.zh    
        }
    });
}

但它不起作用。我需要为描述,营养和brand_names这样做。有人请帮忙。谢谢  This is the screenshot of the json I am getting after GET request

1 个答案:

答案 0 :(得分:1)

如果这是你的对象

var yourObject = [ 
  "description": {
      "zh": "CDes",
      "en": "EDes"
  },
  "nutrition": {
      "zh": "CNutrition",
      "en": "ENutrition"
  },
  "brand_names": {
      "zh": "chineseBName",
      "en": "englishBName"
  }
]

您可以通过

获取zh对象
  var obj = {
    'zh' : yourObject[0].description.zh
};

您的Initial对象是一个数组