Kingsley CA
Kingsley CA

Reputation: 11624

Javascript object not appending new attribute

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

Upvotes: 2

Views: 326

Answers (4)

Kingsley CA
Kingsley CA

Reputation: 11624

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

Upvotes: 0

Yom T.
Yom T.

Reputation: 9190

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

Upvotes: 0

Prince Hernandez
Prince Hernandez

Reputation: 3731

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

Upvotes: 2

cojack
cojack

Reputation: 2620

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

Upvotes: 0

Related Questions