0

I am trying to add one new key-value pair to json object using JavaScript for loop but its not working as expected. I am explaining my code below.

for (var i=0; i < CustomerGroup.length; i++) {
            const customerCollection = loadMongoModel(CUSTOMERS_COLLECTION);
            const data = await customerCollection.find({_id: CustomerGroup[i]['CustomerId']});
            //console.log('data', data);
            CustomerGroup[i].CustomerName = data[0]['CustomerFullName'];
            console.log('data', data[0]['CustomerFullName']);
}
let result = {'record': CustomerGroup, 'count': CustomerGroupCount};
console.log('cust', result);

Here I need to add CustomerName key to CustomerGroup json object but it can not add this key and its value. I need after fetching some data the new value will be assigned to this json object with new key name.

user_agent
  • 65
  • 9
  • what is the result of `console.log('data', data[0]['CustomerFullName']);` – M14 Feb 01 '20 at 05:16
  • @M14: one name is coming. Value is there. – user_agent Feb 01 '20 at 05:19
  • I don't see any problem with the method. May be fetching method issue. https://jsfiddle.net/8xke46oj/ – M14 Feb 01 '20 at 05:22
  • Yes, I am doing the same thing but its not working for me. – user_agent Feb 01 '20 at 05:24
  • @user_agent What do you mean "one name is coming. Value is there"? What is happening? – Brett East Feb 01 '20 at 05:56
  • @BrettEast: question was `what is the result of console.log('data', data[0]['CustomerFullName']);` and I replied its printing one value. – user_agent Feb 01 '20 at 06:00
  • @user_agent yes, but what are you expecting? What is the issue? You say it's not working as expecting, so what do you expect and what is it actually doing? – Brett East Feb 01 '20 at 06:02
  • You can see my question. I need to add new key value pair to existing json. – user_agent Feb 01 '20 at 06:11
  • I mean you haven't really explained what is going wrong. Anyway, the issue is that you're waiting for a value to return from an asynchronous call and a for loop won't wait before moving onto the next iteration, so my guess is only the last `CustomerGroup` customer name is being set, or they're all being set to the same thing - again, I'm trying to ask what result you get so that I can help answer. Check out this answer https://stackoverflow.com/questions/11488014/asynchronous-process-inside-a-javascript-for-loop – Brett East Feb 01 '20 at 06:15

0 Answers0