我有以下JSON数组
var feeds = {"data":[{"id":"128811893769_10152115787143770"},{"id":"128811893769_10152115787143770"}]}
如何将新的密钥和值添加到json中,即(likes_count,share_count)
$.each(feeds.data, function (i, item) {
$.getJSON("facebook_feeds.php?result_type=getCounts&id="+item.id,
function(summary) {
var likesCount = summary[0].like_info.like_count;
var shareCount = summary[0].share_info.share_count;
});
});
我想将键和值推送到feed数组
答案 0 :(得分:0)
试试这个
feeds.data.push({"likesCount": likesCount});
feeds.data.push({"shareCount": shareCount});
答案 1 :(得分:0)
有两种方法。
1.直接在item
[项目持有当前feed.data元素]中添加likesCount和shareCount
OR
2.使用jQuery的extend
方法,(我不建议将它用于这样简单的事情)
$.each(feeds.data, function (i, item) {
$.getJSON("facebook_feeds.php?result_type=getCounts&id="+item.id,
function(summary) {
var likesCount = summary[0].like_info.like_count;
var shareCount = summary[0].share_info.share_count;
// Approach 1
item['likesCount'] = likesCount;
item['shareCount'] = shareCount;
// Approach 2
$.extend ( item, { 'likesCount' : likesCount , 'shareCount' : shareCount } );
});
});
答案 2 :(得分:0)
push()替代方案是联系替代方案,它使您有机会同时使用 jQuery 和 javascript
/*
* Extend Array extra json
* Example:
* $.extendArray([{a:1,b:2}],[{c:3,d:4}]) return -> [{a:1,b:2},{c:3,d:4}]
* $.extendArray([{a:1,b:2}],{c:3,d:4}) return -> [{a:1,b:2},{c:3,d:4}]
*
*/
$.extend({
extendArray: function() {
return Array.prototype.concat.apply([], arguments);
}
});
// Array inside json
var arr = $.extendArray([{a:1,b:2}],[{c:3,d:4},{e:4,f:5},{g:6,h:7}]);
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>