Concatenating objects in jQuery

Sample script .

$('#send').click(function(){
    var object = {}; 
    var chat = {};
    chat = {msg:$('#message').val()};
    var pic = $('.pic');
    object = pic.map(function(){
         var src = $(this).attr('src'),
             tid = $(this).data('id'),
           title = $(this).attr('title'); 
         return  {src:src,tid:tid,title:title}       
      }).get();
    var newobj = $.extend(chat,object);
      console.log(JSON.stringify(newobj));
});

      

The code combines two objects chat

and object

into one object. This is how it looks afterJSON.stringify

 {"0":{"src":"pic.jpg","tid":3,"title":"logo"},
  "1":{"src":"pic2.jpg","tid":3,"title":"logo2"},
  "msg":"dfdfdf"
 }

      

Is it possible to combine objects into this:

 {
  "0":{"msg":"dfdfdf"},
  "1":{"src":"pic.jpg","tid":3,"title":"logo"},
  "2":{"src":"pic2.jpg","tid":3,"title":"logo2"}
 }

      

I tried function chat[0] = {msg:$('#message').val()};

and map

, but it doesn't even merge object chat

into object object

.

HTML:

  <div class="area">
  <button>Choose Picture</button>
</div>

      

+3


source to share


1 answer


You can remove and re-insert it

var newobj = $.extend(chat,object);
delete newobj.msg; // delete the property
newobj["0"] = chat; // add the property
console.log(JSON.stringify(newobj));

      



And since you are using Numbers as property names or IDs, it would be better if this was Array

instead Object

.

+3


source







All Articles