0

I have an object similar to the sample object below.

var obj = {
 id : "",
 entries: [
  {
    url : "some url",
    response : {a response object}
  },
  {
    url : "another url",
    response : {a response object}
  }
 ]
};

In the above object I have an entries element which is an array of object. Each object inside entries element will have a 'url' property and a 'response' property which is an object.

In the object there can be missing response property in entries. In such instance, I have a default response object in a variable 'tempObj' and I assign this tempObj to the 'entries' element.

var tempObj = {
 status : 200
 statusText : "Success"
};

obj.entries[1]["response"] = tempObj;

The problem is when there are multiple response elements missing in obj it adds a response element correctly for the first missing entries, but for the second entries it adds a reference to the first element added.

I need to add the exact value in the second element as well. How can I do this?

This is in nodejs application (not client side javascript).

try-catch-finally
  • 7,436
  • 6
  • 46
  • 67
nzhmz
  • 259
  • 1
  • 2
  • 9

1 Answers1

0

Just loop through the entries array, and update where necessary. For example:

var tempObj = {
    status : 200,
    statusText : "Success"
};

obj.entries.forEach(function(item){
    item.response = item.response || tempObj;
});

If you need the default response to be unique for each item, then just use your favourite cloning method, and apply it on the assignment line. eg, see here: What is the most efficient way to deep clone an object in JavaScript?


Update: When I need to do cloning, or anything for that matter that is common but extends regular js, I usually turn to lodash. You an clone easily with this library, and it works on both node.js and frontend clients. To clone you would do something like:

item.response = item.response || _.assign({}, tempObj); 
Community
  • 1
  • 1
Matt Way
  • 32,319
  • 10
  • 79
  • 85
  • this is a nodejs code. Most of the cloning methods you suggested uses jQuery. – nzhmz Oct 26 '15 at 04:54
  • No Hamza, it's not jQuery. [`forEach` is ECMAScript 5.1](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Specifications). But what's actually missing in this answer is the cloning. :) – try-catch-finally Oct 26 '15 at 05:10
  • [This is a good pur Javascript clone() implementation](http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object/122190#122190) I think. – try-catch-finally Oct 26 '15 at 05:15
  • @Hamza, I updated the answer to include an example of how could do the cloning, and it works for both node.js and client code. You really need to add node.js tags to your question if that is accurate. – Matt Way Oct 26 '15 at 05:40
  • @MattWay, Thanks for your response. Much helpful. – nzhmz Oct 26 '15 at 09:29