0

I need to merge these two objects to get below output using JS. Thanks in advance and its ok to use jquery library if needed

var defaultOptions = {
        count:3
    };
    
    var JSON = {
      one:{
        title:"something",
        count:15
      },
      two:{
        title:"another"
      }
    }
    
    // expecting
    
    var JSON = {
      one:{
        title:"something",
        count:15
      },
      two:{
        title:"another",
        count:3
      }
    }
Dhanan
  • 207
  • 4
  • 12
  • I don't need to iterate the whole object to accomplished this task – Dhanan Mar 30 '17 at 05:28
  • ok, so what do you want – Jaromanda X Mar 30 '17 at 05:28
  • [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/), [What is the difference between JSON and Object Literal Notation?](http://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Mar 30 '17 at 05:30
  • @JaromandaX I need to get the expected out ( with the default value ), Originally there is no count value in "two" object. – Dhanan Mar 30 '17 at 05:33
  • @Dhanan please checkout https://stackoverflow.com/help/how-to-ask – Jameson Mar 30 '17 at 05:36
  • You can use `for..in` loop to check if object has `"count"` property, if false, set `"count"` property of default object to object – guest271314 Mar 30 '17 at 05:38

3 Answers3

1

Try this.

var defaultOptions = {
        count:3
    };
    
    var someObject = {
      one:{
        title:"something",
        count:15
      },
      two:{
        title:"another"
      }
    }
    
   for (var property in someObject) {
    if (someObject[property].count == undefined) {
       console.log(someObject[property]);
       someObject[property].count = defaultOptions.count;
       console.log(someObject[property]);
    }
}
Dhiraj
  • 1,430
  • 11
  • 21
  • You could also use `in` operator at `if` condition `for (var prop in JSON) { if (!("count" in JSON[prop])) JSON[prop]["count"] = defaultOptions["count"] }` – guest271314 Mar 30 '17 at 05:48
0

You can use $.extend to merge objects.

    for (var key in JSON) {
       if (!JSON[key]['count']){
          $.extend(JSON[key], defaultOptions);
       }
    }

Update: Loop through the object and check for count object

Cara
  • 634
  • 5
  • 10
0

It's like this:

function mergeObjs(){
  var a = [].slice.call(arguments), o = a.shift();
  for(var i=0,l=a.length; i<l; i++){
    for(var p in a[i]){
      o[p] = a[i][p];
    }
  }
  return o;
}
console.log(mergeObjs({neat:'totally'}, {cool:'works', someAry:[1,7,5,'test']}, {what:'now', really:7}));
StackSlave
  • 10,613
  • 2
  • 18
  • 35