3

Fiddle Example.

$('#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 single object. This is how it looks like after JSON.stringify

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

Is it possible to merge the objects into this:

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

I have tried chat[0] = {msg:$('#message').val()}; and map function but it doesn't even merge the chat object into the object object.

HTML:

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

2
  • 9
    why not to use array instead object? {'0': {msg}} -> [{msg}] ? Commented Dec 11, 2014 at 8:25
  • object.unshift(chat); jsfiddle.net/yee4b1uu/28 ??? Commented Dec 11, 2014 at 8:42

1 Answer 1

3

You could delete and reinsert 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're using Numbers as the property names or identifiers, it would be better suited if it were an Array instead of an Object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.