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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With