【问题标题】:Find and update JSON object using Typescripts使用 Typescript 查找和更新 JSON 对象
【发布时间】:2018-08-31 01:01:57
【问题描述】:
下面是我的 JSON
[{ "id": "1",
"name" : "rob",
"Lastname":"Xyz"
},
{ "id": "2",
"name" : "xyz",
"Lastname":"abc"
}]
我有一个表单,用户将在其中输入他的名字和姓氏,我在这里想要实现的是检查用户输入信息是否在 JSON 中可用。如果是,则更新用户信息,否则使用 .push() 添加新对象
【问题讨论】:
标签:
json
angular
typescript
【解决方案1】:
也许这会对你有所帮助:
export class Test {
// Objects array
myObjects = [{ "id": "1",
"name" : "rob",
"Lastname":"Xyz"
},
{ "id": "2",
"name" : "xyz",
"Lastname":"abc"
}]
// Method responsible for finding an object who has the name passed in as a parameter
getIndexByName(name: string): number{
let index: number;
this.myObjects.forEach(object => {
if(object.name == name){ // Do your filtering here
index = this.myObjects.indexOf(object);
}
})
return index;
}
updateObject(obj: any){
let index = this.getIndexByName(obj.name);
if(index){
this.myObjects.splice(index,1,obj); // This is the usual function that I use when I find myself needing to 'update' something in an array
}
}
}
你可以这样使用它:
let user = {"id": "2", "name" : "xyz", "Lastname":"yjk"};
this.updateObject(user);
【解决方案2】:
interface User {
id: string;
name: string;
Lastname: string;
}
class UsersCollection {
private id = 15;
constructor(private _users: Array<User> = []) {
}
public create(name: string, lastName: string): User {
let user = {
id: this.id++,
name: name,
Lastname: lastName
};
this._users.push(user);
return user;
}
public searchUser(name: string, lastName: string): User | null {
return this._users.find((user) => {
return user.name == name && user.Lastname == lastName;
})
}
public getOrCreate(name: string, lastName: string) {
let user = this.searchUser(name, lastName);
if (user) {
return user;
}
return this.create(name, lastName);
}
public size(){
return this._users.length;
}
}
let users = new UsersCollection([{
'id': '1',
'name': 'rob',
'Lastname': 'Xyz'
},
{
'id': '2',
'name': 'xyz',
'Lastname': 'abc'
}]);
// Existing user
console.log(users.getOrCreate('rob','Xyz'));
console.log(users.size() == 2);
// Add new one
console.log(users.getOrCreate('rob','123'));
console.log(users.size() == 3);