我有json文件,数据就像这样
[{"wingnum":0,"name":"vatsal chauhan","email":"chauhanvatsal81@yahoo.com","city":"bhavnagar","address":"asdf"},
{"wingnum":0,"name":"hardik","email":"hardikdave@gmail.com","city":"GANDHINAGAR","address":"Gandhinagar"},
{"wingnum":0,"name":"kevin","email":"kevin@gmail.com","city":"GANDHINAGAR","address":"Gandhinagar"},
{"wingnum":0,"name":"rohit","email":"rohit@gmail.com","city":"GANDHINAGAR","address":"Gandhinagar"}]
我想使用fs.readfile或任何其他选项搜索名称,我的代码如下所示
exports.getdata = function(req,res,next){
console.log('reqobj',req.body.params.name);
fs.readFile('./server/api/Appartment/appartment.json', 'utf8',function read(err, data) {
/*obj = JSON.parse(data);
console.log(obj);*/
if (err) {
throw err;
}
else{
if (data === ""){
console.log('data does not exsist');
}
else{
console.log('exsist data getdata');
var arrayobject = JSON.parse(data);
console.log(arrayobject);
return res.status(200).json(data);
}
}
// res.end();
});
};
此代码提供所有数据,但我想根据传递的参数获取名称 像自动完成
答案 0 :(得分:0)
一旦解析了JSON并将对象放在变量中,就要在此函数中传递要搜索的对象和名称:
var searchname=function(x, somename){
for(var i = 0; i < x.length; i++) {
if (x[i]['name']==somename){
return i;
}
}
return -1; //This means no match found
}
例如,您可以在代码中获取包含所需名称的文档:
var index=searchname(arrayobject, req.body.params.name);
if (index!=-1){
console.log(json[index]);
// Or do something else with json[index]
}
更新:如果你想在对象本身内进行搜索,并获得符合条件的所有名称,那么函数将如何改变:
var searchname=function(x, somename){
var result=[];
for(var i = 0; i < x.length; i++) {
if (x[i]['name'].indexOf(somename)>-1){
result.push(x[i]['name']);
}
}
return result; //Array containing matched names. Returns empty array if no matches found.
}
console.log(searchname(arrayobject, req.body.params.name)); //To display the working of above for testing.