尝试映射两个数组值。一个数组值来自本地Json文件,其他数组值来自服务或后端。
本地JSON:
var localJsonArray = {
"records": {
"cat1": [{
"id": 1234,
"label": "a"
}, {
"id": 2345,
"label": "b"
}],
"cat2": {
"id": 12345,
"label": "c"
}
}
}
后端数组值:
我将来自后端的值存储为:
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 );
}
});
现在我如何将本地Json的id映射到后端JSON的id。如果值匹配,则循环应该破坏else,它应该查找值。
答案 0 :(得分:1)
您无法创建像var backendArray =[0: "1234", 1: "3456", 2:"4567"];
顺便说一下......按照上面的代码:
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 );
}
}
});
希望这有帮助!!! :)