[英]How can I add more data to an json based object in Typescript?
I am trying to add more things inside an object but I am not sure how to do it 我正在尝试在一个对象中添加更多东西,但是我不确定该怎么做
I have tried pushing the data into the object but it doesn't work 我尝试将数据推入对象中,但不起作用
people = [{
name: 'robert',
year: 1993
}];
//this is what i want to add //这就是我要添加的
people = {
name: 'joe',
year: 1992
}
//I want it to act as if it was //我希望它像
people = [{
name: 'robert',
year: 1993
}, {
name: 'joe',
year: 1992
}];
I want to be able to call it back using people[0].name 我希望能够使用people [0] .name进行回叫
Assuming you want the people
variable to be an array of objects, 假设您希望
people
变量是一个对象数组,
const people = [{ name: 'robert', year: 1993 }];
If you want to add an object to people
, 如果您想向
people
添加对象,
const newPerson = { name: 'joe', year: 1992 };
people.push(newPerson);
And if you want to access the individual objects/properties, 如果您要访问单个对象/属性,
people[0];
people[0]['name'];
Regarding your subsequent issue, you may want to provide the type definitions for people
. 关于您的后续问题,您可能需要为
people
提供类型定义。
export class AppComponents {
// your properties and methods
}
interface Person {
name: string;
year: number;
}
On your main code itself, you can declare the variables with the typings. 在您的主代码本身上,您可以使用类型声明变量。
const people: Person[] = [{ name: 'robert', year: 1993 }];
const newPerson: Person = { name: 'joe', year: 1992 };
people.push(newPerson);
尝试这个
people.push({ name: 'joe', year: 1992 });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.