SQL style JOIN on JSON data

后端 未结 3 1277
Happy的楠姐
Happy的楠姐 2020-12-16 13:51

Is there any way efficiently to join JSON data? Suppose we have two JSON datasets:

{\"COLORS\":[[1,red],[2,yellow],[3,orange]]}

{\"FRUITS\":[[1,apple],[2,ba         


        
3条回答
  •  一向
    一向 (楼主)
    2020-12-16 14:44

    There is not a direct way, but you can write logic to get a combined object like this. Since "apple, red, banana...." are all strings, they should be wrapped in a single or double quote.

    If you can match the COLORS and FRUITS config array by adding null values for missing items then you can use this approach.

    Working demo

    var colors = {"COLORS":[[1,'red'],[2,'yellow'],[3,'orange']]}
    
    var fruits = {"FRUITS":[[1,'apple'],[2,'banana'],[3,'orange']]}
    
    var newFruits = {"NEW_FRUITS": [] }
    
    //Just to make sure both arrays are the same size, otherwise the logic will break
    if(colors.COLORS.length == fruits.FRUITS.length){
        var temp;
        $.each(fruits.FRUITS, function(i){
            temp = this;
            temp.push(colors.COLORS[i][2]);
            newFruits.NEW_FRUITS.push(temp);
        });
    }
    

    Alternatively, if you can create colors and fruits configs as an array of objects, instead of an array of arrays, you can try this solution. The sequence of the elements is irrelevant here, but the array size should still match.

    Working demo

    var colors = {"COLORS":[ {"1": 'red'}, { "2": 'yellow'}, {"3":'orange'}]}
    
    var fruits = {"FRUITS":[ {"1":'apple'}, { "2": 'banana'}, {"3":'orange'}]}
    
    var newFruits = {"NEW_FRUITS": [] }
    
    if(colors.COLORS.length == fruits.FRUITS.length){
        var temp, first;
        $.each(fruits.FRUITS, function(i){
            for(first in this)break;
            temp = {};
            temp[first] = [];
            temp[first].push(this[first]);
            temp[first].push(colors.COLORS[i][first]);
            newFruits.NEW_FRUITS.push(temp);
        });
    }
    

提交回复
热议问题