比较两个json数据数组对象

时间:2014-10-14 11:39:23

标签: jquery json

一个JSON对象包含一个Ids数组,另一个包含每个数组中包含id和title的数组数组。这是我的两种JSON数据格式......

第一个JSON数据:

json1 : [
        "123",
        "456",
        "789"
]

第二个JSON数据:

json2 : [
    [
        "789",
        "Title3"
    ],
    [
        "456",
        "Title2"
    ],
    [
        "123",
        "Title1"
    ]
]

因此,比较上述两个JSON数据的ID顺序,需要创建一个带有标题名称的新JSON数据。所以最终的JSON应该遵循这些....

最终输出:

[
    'Title1',
    'Title2',
    'Title3'
]

请建议我。

3 个答案:

答案 0 :(得分:0)

你可以这样做

var titleArr = json2.filter(function(x) {
    return json1.indexOf(x[0]) != -1; // checking if the both contain same ids
}).map(function(x) {
    return x[1]; // returns just the second element which is title
});

答案 1 :(得分:0)

var json1 = JSON.parse('["123", "456", "789" ]');

var json2 = JSON.parse('[["789", "Title3"],["456","Title2"],["123","Title1"]]');

var titleArr = []; 

for(var i=0; i<json1.length; i++){
    for(var j=0; j<json2.length; j++){
        if(json2[j][0] == json1[i])
        titleArr.push(json2[j][1]);
    }
}

答案 2 :(得分:0)

你可以这样做:

   <script>

    json1='{"json1":["123","456","789"]}';
    obj1 = JSON.parse(json1);       

    json2='{"json2":[{"789":"Title3"},{"456":"Title2"},{"123":"Title1"}]}';     
    obj2 = JSON.parse(json2);

    var resultArray=[];

    for(i=0;i<obj1['json1'].length;i++)
    {
        id=obj1['json1'][i];

        for(j=0;j<obj2['json2'].length;j++)
        {           
            if(typeof obj2['json2'][j][id] !== "undefined")
            {
                resultArray.push(obj2['json2'][j][id]);
            }
        }
    }

    console.log(resultArray);   //FINAL RESULT ARRAY

  </script>