在 jQuery 中合并对象

Merging objects in jQuery

本文关键字:对象 合并 jQuery      更新时间:2023-09-26

小提琴示例。

$('#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));
});

该代码将两个对象chatobject合并为一个对象。这就是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>

您可以删除并重新插入它

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,它会更合适。