0

Here is what I have tried. I have tried dot notation and quotes. None of them seem to work. What exactly could be the problem?

var clientsList;

Client.find({}, function(err, clients) {
    clientsList = clients; 
   // I have 10 clients in the loop 
   for (var j = 0; j < clientsList.length; j++) {
            var x =  clientsList[j];
            x.count = "20";
            //x["count"] = "20";
            console.log(x);
        }

});

Existing Client object

{"name":"abcd", "email":"abc@gmail.com"}

I'm unable to add the count key value pair into the client object. What could be the problem?

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
Anirudh
  • 2,767
  • 5
  • 69
  • 119
  • Are the objects non-extensible or something? Not enough in the existing code to tell – CertainPerformance Sep 13 '18 at 07:38
  • 1
    There's no JSON in your question at all. JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Sep 13 '18 at 07:39
  • @CertainPerformance sorry, updated query. – Anirudh Sep 13 '18 at 07:39

1 Answers1

0

I suspect the object you're being given by Client.find has extensions prevented (it's sealed or frozen).

You can create a new object with the original's own, enumerable properties plus your count property using ES2018 spread notation:

x = {...x, count: "20"};

...or ES2015's Object.assign:

x = Object.assign({}, x, {count: "20"});

If the array is also sealed or frozen, you can copy it and its objects like this:

clientList = clients.map(client => {
    return {...client, count: "20"}; // Or with `Object.assign`
});

or even with the concise form of the arrow function:

clientList = clients.map(client => ({...client, count: "20"}));

Side note: This pattern:

var clientsList;
Client.find({}, function(err, clients) {
    clientsList = clients; 
    // ...
});

...often suggests that you intend to use clientsList in code following the Client.find call and expect it to have the result from that call's callback. See this question's answers for why, if you're doing that, it doesn't work.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875