获取json对象的id或者根据name获取id

时间:2022-02-07 18:24:12

--用json的时候,知道id获取对应的name或者相反根据name获取id

--内核代码

 <script>
var products=[{ID:1,Name:"a",Price:1},{ID:2,Name:"b",Price:4}];
for(var s in products)
{ alert("ID是:"+products[s].ID+"Name是:"+products[s].Name); }
</script>

products[索引]获得json数组对象,然后 对象.属性 获得属性值。

--两个方法:

--1、idToName

function idToName(jsonList,id)
{
var schools = jsonList[0].school;
var name = '';
for(var s in schools) {
var getId = schools[s].id ;
var getName = schools[s].name;
if (getId = id ) name = getName ;
};
return name ;
}

--2、nameToId

function nameToId(jsonList,name)
{
var schools = jsonList[0].school;
var id = '';
//alert(name);
for(var s in schools) {
var getId = schools[s].id ;
var getName = schools[s].name;
//alert('getId='+getId);
//alert('gegName='+getName);
//alert (getName + name);
//alert (getName == name);
if (getName == name ) {
id = getId;
//alert('findid='+id);
return id;
} ;
};
}