在Javascript中使用键值推送两个数组

时间:2014-04-16 06:27:46

标签: javascript arrays

我有两个数组第一个数组 connections Array

[
    {
        account_id: '1000024965925119facebook',
        account_name: 'JijoJohn',
        account_image: '5133_a.jpg',
        account_type: 'facebook'
    },
    {
        account_id: '100002496592511facebook',
        account_name: 'JijoJohn',
        account_image: '55133_a.jpg',
        account_type: 'facebook'
    },
    {
        account_id: '138115932930527facebook',
        account_name: 'JijoJohn',
        account_image: '5555133_a.jpg',
        account_type: 'facebook'
    },
    {
        account_id: '101706396580621facebook',
        account_name: 'JijoJohn',
        account_image: '55133_a.jpg',
        account_type: 'facebook'
    },
    {
        account_id: 'feed1',
        account_name: 'JijoJohn',
        account_image: '5555133_a.jpg'
    },
    {
        account_id: '57880525twitter',
        account_name: 'MinuJose',
        account_image: 'b4_normal.png',
        account_type: 'twitter'
    }
]

count Array

[
    {
        type: 'facebook',
        count: 4
    },
    {
        type: 'twitter',
        count: 1
    }
]

这里将第二个数组推入第一个数组

connections.push(count);

我的要求是如何将键值添加到连接数组中,如下所示。我需要在每个数组之前添加帐户和计数键。请帮我找一个解决方案。谢谢

{ 
    "accounts" : 
    [
        {
            account_id: '57880525twitter',
            account_name: 'MinuJose',
            account_image: 'b4_normal.png',
            account_type: 'twitter'
        },
        {
              account_id: '57880525twitter',
            account_name: 'MinuJose',
            account_image: 'b4_normal.png',
            account_type: 'twitter'
        }
    ],
    "count" :
    [

        {
            "type":"facebook",
             "count": 4
        } ,
         {
            "type":"twitter",
            "count": 1
        } 
    ]
}

2 个答案:

答案 0 :(得分:1)

你想要创建一个新对象,而不是一个数组:

  new_object = {
     "accounts" : account_array,
     "count": count_array
  }

答案 1 :(得分:1)

你可以这样做

 var result = {
    accounts: accountsArray,
    counts: countsArray
 }

 (or)

 var result = {
 }
 result.accounts = accountsArray;
 result.counts = countsArray.

您不需要array.push