$('#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));
});
代码将两个对象chat
和object
合并为一个对象。这就是JSON.stringify
{"0":{"src":"pic.jpg","tid":3,"title":"logo"},
"1":{"src":"pic2.jpg","tid":3,"title":"logo2"},
"msg":"dfdfdf"
}
是否可以将对象合并到此:
{
"0":{"msg":"dfdfdf"},
"1":{"src":"pic.jpg","tid":3,"title":"logo"},
"2":{"src":"pic2.jpg","tid":3,"title":"logo2"}
}
我尝试了chat[0] = {msg:$('#message').val()};
和map
函数,但它甚至没有将chat
对象合并到object
对象中。
HTML:
<div class="area">
<button>Choose Picture</button>
</div>
答案 0 :(得分:3)
您可以删除并重新插入
var newobj = $.extend(chat,object);
delete newobj.msg; // delete the property
newobj["0"] = chat; // add the property
console.log(JSON.stringify(newobj));
由于您使用Numbers作为属性名称或标识符,因此如果它是Array
而不是Object
,则更适合。