从多个阵列构建自定义JSON数组

时间:2014-06-20 19:38:01

标签: javascript jquery ruby-on-rails arrays json

我从facebook和twitter的API中获取了用户朋友的列表。

var facebook_friends = { "data": [{"name": "Friend Joe", "id": "123"}, {"name": "Friend Jane", "id": "12342"}]}
var twitter_friends = { "users": [{"name": "Other friend joe", "id": "333"}, {"name": "Other friend Jane", "id": "456"}]}

我想构建一个这样的数组(Nb:我附加了提供者密钥来识别数据的来源)

var all_friends = [{"name": "Friend Joe", "id": "123", "provider": "facebook"},{"name": "Friend Jane", "id": "12342", "provider": "facebook"}, {"name": "Other friend joe", "id": "333", "provider": "twitter"},{"name": "Other friend Jane", "id": "456", "provider": "twitter"}]

感谢。

1 个答案:

答案 0 :(得分:4)

var facebook_friends = { "data": [{"name": "Friend Joe", "id": "123"}, {"name": "Friend Jane", "id": "12342"}]};

$.map(facebook_friends.data, function($item) {
    $item['provider'] = 'facebook';
    return $item;    
});

var twitter_friends = { "users": [{"name": "Other friend joe", "id": "333"}, {"name": "Other friend Jane", "id": "456"}]};

$.map(twitter_friends.users, function($item) {
    $item['provider'] = 'twitter';
    return $item;    
});

var all_friends = $.merge(facebook_friends.data, twitter_friends.users);

console.log(all_friends);

DEMO