【问题标题】:Javascript object not appending new attributeJavascript对象不附加新属性
【发布时间】:2019-06-21 15:14:00
【问题描述】:

我有这个函数,我在其中检索一个对象数组,然后我有一个 for 循环来循环遍历对象,并向它附加一个索引或 ind 属性:

module.exports.getCustomers = async (req, res) => {
  let customers = await Customers.find({}, { "_id": 1 });

  for (var i = 0; i < customers.length; i++) {
    customers[i].ind = i;
  }

  console.log(customers)
}

但是当我运行它时,数据返回为

[
  { _id: ... },
  { _id: ... },
  ...
]

代替:

[
   {_id: ..., ind: 0},
   {_id: ..., ind: 1},
   ...
]

请问我该如何解决这个问题

【问题讨论】:

  • 你试过Object.assign吗?
  • 所提供的代码没有问题,您可以给我们提供有关 Customers.find() 的更多信息
  • 试试这个:await Customers.find({}, { "_id": 1 }).toArray();
  • 能否提供await Customers.find({}, { "_id": 1 })的值?这样更容易提供解决方案。
  • Customers.find()returns a cursor,你会find here如何正确使用它

标签: javascript arrays node.js mongodb javascript-objects


【解决方案1】:

更改您的 for 并将其变成 map

module.exports.getCustomers = async (req, res) => {
  let customers = await Customers.find({}, { "_id": 1 });

  let mappedCustomers = customers.map((customer, index) => {
              customer['ind'] = index;
              return customer;
          });


  console.log(mappedCustomers);
  return mappedCustomers;
}

您也可以创建一个全新的客户。

let mappedCustomers = customers.map((customer, index) => {
              return {...customer, ind: index};
              });

【讨论】:

    【解决方案2】:

    您的对象似乎被冻结了,不知道您使用什么库从数据源中获取这些项目,但您可以在此处阅读有关对象冻结的信息 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

    【讨论】:

    【解决方案3】:

    尝试使用Object.assign 将值复制到各个目标对象。

    module.exports.getCustomers = async(req, res) => {
      let customers = await Customers.find({}, {
        "_id": 1
      });
    
      for (var i = 0; i < customers.length; i++) {
        Object.assign(customers[i], {
          ind: i
        });
      }
    
      console.log(customers);
    }
    

    【讨论】:

      【解决方案4】:

      我终于解决了。我认为mongoose 搞砸了。但是添加._doc 似乎已经修复了它

      for (let i = 0; i < customers.length; i++) {
      
          let customer = customers[i], 
      
          customer._doc = {
            ...customer._doc,
            index: i
          };
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-24
        • 1970-01-01
        • 2018-01-28
        • 2012-05-01
        • 1970-01-01
        • 2012-03-16
        • 2016-07-13
        • 2018-07-24
        相关资源
        最近更新 更多