我试图在javascript / jQuery中将新值(从外部json文件)映射到数组(数组或KV对的数组,从php文件查询到mysql生成)。 数组的结构是:
"results":
[{"gender":"Male","DOB":"1993-09-22","location":"Main","procCode":"43653","preopDx1":"783.3","procedDate":"2008-06-02"},{"gender":"Female","DOB":"2001-11-07","location":"South","procCode":"11403","preopDx1":"216.5","procedDate":"2010-01-01"},...]
json文件如下所示:
[ { “CPT”:“10021”, “RVU”:“1.27” }, { “CPT”:“10022”, “RVU”:“1.27” } ]
想法是
a)循环通过myarray值并找到每个procCode
b)将此procCode与json文件中相同的cpt代码匹配,并
c)将每个新的键/值对附加到myarray的每一行'/ p>
function addRVU (myarray, myjson){
var newObj = $.map(myarray, function (i,res){
if(myarray[i].procCode == myjson[i].CPT){
return myarray[i].RVU = myjson[i].RVU;
}
}
}
提前致谢!
答案 0 :(得分:0)
// First, convert JSON file into an object keyed off CPT code:
var jsonObj = {};
for (var i = 0; i < json.length; i++) {
jsonObj[json[i].CPT] = json[i];
}
// Now update myarray elements
for (i = 0; i < myarray.length; i++) {
// $.extend copies properties from 2nd object into 1st object
$.extend(myarray[i], jsonObj[myarray[i].procCode]);
}
答案 1 :(得分:0)
对于if(myarray[i].procCode == myjson[i].CPT)
,您只将json和数组与相同的索引匹配。循环以匹配json中的所有元素应该解决您的问题。
或类似使用哈希来映射RVU
h = {};
$.each(json, function(i, e){
h[e.CPT] = e.RVU;
});
$.each(ar, function(i, e){
e.RVU = h[e.procCode];
});