0

trying to map two Array Values. One Array Values are coming from the local Json file and other array values are coming from the service or backend.

Local JSON:

var localJsonArray = {
    "records": {
        "cat1": [{
            "id": 1234,
                "label": "a"
        }, {
            "id": 2345,
                "label": "b"

        }],
            "cat2": {

            "id": 12345,
                "label": "c"
        }
    }
}

Backend Array Values:

I am storing the value coming from backend as:

var backendArray =[0: "1234", 1: "3456", 2:"4567"];

JS:

$.each( localJsonArray, function( key, value ) {
                var index = $.inArray( value, backendArray );
                if( index != -1 ) {
                    console.log( index );
                }
            });

Now how do I map the id of local Json to the id of backend JSON. If value matches the loop should break else it should look for the value.

3
  • where is the backend array values? Commented Jun 18, 2014 at 11:46
  • You can't create an array like that >>> 'var backendArray =[0: "1234", 1: "3456", 2:"4567"]'; Commented Jun 18, 2014 at 11:53
  • But I'll create the answer... ;) ... wait a moment Commented Jun 18, 2014 at 11:53

1 Answer 1

1

You can't create a array like var backendArray =[0: "1234", 1: "3456", 2:"4567"];

So by the way ... follow the code above:

var localJsonArray = {
    "records": {
        "cat1": [{
            "id": 1234,
                "label": "a"
        }, {
            "id": 2345,
                "label": "b"

        }],
            "cat2": {

            "id": 12345,
                "label": "c"
        }
    }
};
var backendArray =["1234", "3456", "4567"];

$.each( localJsonArray['records'], function( a,b,c ) {
    if(!(b.length == undefined)){
        for(var i = 0;i < b.length; i++)
        {
            var index = $.inArray( b[i].id.toString(), backendArray );
            if( index != -1 ) {
                console.log( index );
            }
        }
    }
    else{
        var index = $.inArray( b.id.toString(), backendArray );
        if( index != -1 ) {
            console.log( index );
        }
    }
});

Hope this help!!! :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.