JavaScript对象的数组:如果满足条件,则更改一个键的值和数据类型

时间:2021-08-28 02:34:20

I'm pulling some data from a MongoDB collection using Mongoose. I'm getting back my array of objects with just the fields I've selected. All good. Here's my code:

我正在使用Mongoose从MongoDB集合中提取一些数据。我只用我选择的字段取回了我的对象数组。都好。这是我的代码:

var fieldsToReturn = 'username password';
User.find({username: {$exists: true}}, fieldsToReturn, {sort: {'created.when': 1}}, function(err, data){
  if (err) {
    return err;
  } else {
    // clever code needed here to manipulate the data!
    return res.json(data);
  }
});

What I want to do is iterate through the array of JavaScript objects returned in data and if there is a password (it'll be a text string) replace password with a boolean true, but if it's null then return a boolean false.

我想要做的是遍历数据中返回的JavaScript对象数组,如果有密码(它将是文本字符串),用布尔值true替换密码,但如果它为null则返回布尔值false。

I've tried a bit of underscore.js magic:

我尝试了一些underscore.js魔法:

_.each(data, function(element, index, list){
  if (element.password !== null) {element.password = true};
});

But what I get in the JSON that's returned is "password":"true" and not "password":true. Also tried element.password = new Boolean(true). Any suggestions?

但是我在JSON中得到的是“password”:“true”而不是“password”:true。还试过element.password = new Boolean(true)。有什么建议?

3 个解决方案

#1


You could use map for this.

你可以使用map来做这件事。

data = data.map(function(element) {
  if (element.password) {
    element.password = true;
  }
  return element;
});

var data = [
    {
        password: 'secret'
    },
    {
        password: ''
    },
    {
        password: 'swordfish'
    }
];

data = data.map(function(element) {
    if (element.password) {
        element.password = true;
    }
    return element;
});

document.querySelector('pre').innerText = JSON.stringify(data);
<pre></pre>

#2


Try using asyncjs lybrary. It will call the callback function when finished all the executions for the array objects. Please, also read carefully about asyncronous flow in javascript (nodejs) .

尝试使用asyncjs lybrary。完成数组对象的所有执行后,它将调用回调函数。请仔细阅读javascript(nodejs)中的异步流程。

Hope it helps!!

希望能帮助到你!!

 //this should work if placed on your clever code and installed asyncjs
 async.map(data, checkPassword, function(err, results){
  //when arrived here, all the array has been checked and modified
  console.log(results);
 }

 //Remember This function must be placed outside of the find() method. 
 function checkPassword(obj, callback)
 {
   if (obj.password) {
   obj.password = true;
   }
   return callback(null, obj);
 }

#3


It's Mongoose. Something is happening before the data is returned which makes it look like straight JSON but if you try and manipulate the element in a _.each loop then the object you're working on (element) isn't a simple object mapping to the document in MongoDB. Any Mongoose experts out there that can shed light on this?

这是猫鼬。在返回数据之前发生了一些事情,这使得它看起来像直接JSON但是如果你尝试在_.each循环中操作元素,那么你正在处理的对象(元素)不是映射到文档的简单对象在MongoDB中。哪有Mongoose专家可以解释这个问题?

What I did to fix this is use LoDash's _.mapValues:

我为解决这个问题所做的是使用LoDash的_.mapValues:

function renderUserKeys(obj){
  var newObj = _.mapValues(obj, function(n){return n});
  if (newObj.password !== null) {newObj.password = true};
  return newObj;
};

And then in the code:

然后在代码中:

...
} else {
  var newArray = [];
  _.each(data, function(element, index, list){
    newArray.push(renderUserKeys(element._doc)); // note the ._doc
  });
  return res.json(newArray);
};

Maybe there is a better function that _.mapValues (maybe _.merge?) to perform the copy, I'll need to look into this, but for now this works and my Mongoose middleware is still running normally (as I'm not using lean()).

也许有一个更好的函数_.mapValues(也许_.merge?)来执行复制,我需要调查一下,但是现在这个工作并且我的Mongoose中间件仍然正常运行(因为我不是使用lean())。

Lesson learned: Mongoose !== Duck. As in, it may look like an object but when you try and manipulate it, it doesn't behave as you expect it to!

获得的经验:猫鼬!==鸭子。就像在,它可能看起来像一个对象,但当你尝试和操纵它时,它的行为并不像你期望的那样!

#1


You could use map for this.

你可以使用map来做这件事。

data = data.map(function(element) {
  if (element.password) {
    element.password = true;
  }
  return element;
});

var data = [
    {
        password: 'secret'
    },
    {
        password: ''
    },
    {
        password: 'swordfish'
    }
];

data = data.map(function(element) {
    if (element.password) {
        element.password = true;
    }
    return element;
});

document.querySelector('pre').innerText = JSON.stringify(data);
<pre></pre>

#2


Try using asyncjs lybrary. It will call the callback function when finished all the executions for the array objects. Please, also read carefully about asyncronous flow in javascript (nodejs) .

尝试使用asyncjs lybrary。完成数组对象的所有执行后,它将调用回调函数。请仔细阅读javascript(nodejs)中的异步流程。

Hope it helps!!

希望能帮助到你!!

 //this should work if placed on your clever code and installed asyncjs
 async.map(data, checkPassword, function(err, results){
  //when arrived here, all the array has been checked and modified
  console.log(results);
 }

 //Remember This function must be placed outside of the find() method. 
 function checkPassword(obj, callback)
 {
   if (obj.password) {
   obj.password = true;
   }
   return callback(null, obj);
 }

#3


It's Mongoose. Something is happening before the data is returned which makes it look like straight JSON but if you try and manipulate the element in a _.each loop then the object you're working on (element) isn't a simple object mapping to the document in MongoDB. Any Mongoose experts out there that can shed light on this?

这是猫鼬。在返回数据之前发生了一些事情,这使得它看起来像直接JSON但是如果你尝试在_.each循环中操作元素,那么你正在处理的对象(元素)不是映射到文档的简单对象在MongoDB中。哪有Mongoose专家可以解释这个问题?

What I did to fix this is use LoDash's _.mapValues:

我为解决这个问题所做的是使用LoDash的_.mapValues:

function renderUserKeys(obj){
  var newObj = _.mapValues(obj, function(n){return n});
  if (newObj.password !== null) {newObj.password = true};
  return newObj;
};

And then in the code:

然后在代码中:

...
} else {
  var newArray = [];
  _.each(data, function(element, index, list){
    newArray.push(renderUserKeys(element._doc)); // note the ._doc
  });
  return res.json(newArray);
};

Maybe there is a better function that _.mapValues (maybe _.merge?) to perform the copy, I'll need to look into this, but for now this works and my Mongoose middleware is still running normally (as I'm not using lean()).

也许有一个更好的函数_.mapValues(也许_.merge?)来执行复制,我需要调查一下,但是现在这个工作并且我的Mongoose中间件仍然正常运行(因为我不是使用lean())。

Lesson learned: Mongoose !== Duck. As in, it may look like an object but when you try and manipulate it, it doesn't behave as you expect it to!

获得的经验:猫鼬!==鸭子。就像在,它可能看起来像一个对象,但当你尝试和操纵它时,它的行为并不像你期望的那样!