2

I have this function, where I retrieve an array of objects, I then have a for loop to loop through the objects, and append an index or ind attribute to it:

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)
}

but when I run this, the data is returned as

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

instead of:

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

Please how do I fix this

Kingsley CA
  • 10,685
  • 10
  • 26
  • 39

4 Answers4

2

change your for and turn it into a 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;
}

or instead returning the customer, you can create a completly new customer.

let mappedCustomers = customers.map((customer, index) => {
              return {...customer, ind: index};
              });
Prince Hernandez
  • 3,623
  • 1
  • 10
  • 19
0

It looks like your objects are freezed, idk what library you are using to fetch those items from your data source, but you can read about object freezing here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

cojack
  • 2,444
  • 1
  • 17
  • 18
0

Try copying the values over to the individual target objects with 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);
}
Yom T.
  • 8,760
  • 2
  • 32
  • 49
0

I finally solved it. I think mongoose was messing with it. But adding ._doc seems to have fixed it

for (let i = 0; i < customers.length; i++) {

    let customer = customers[i], 

    customer._doc = {
      ...customer._doc,
      index: i
    };
}
Kingsley CA
  • 10,685
  • 10
  • 26
  • 39