【问题标题】:How can I add more data to an json based object in Typescript?如何在 Typescript 中向基于 json 的对象添加更多数据?
【发布时间】:2019-07-03 02:04:03
【问题描述】:

我正在尝试在对象中添加更多内容,但我不知道该怎么做

我尝试将数据推送到对象中,但它不起作用

people = [{
  name: 'robert',
  year: 1993
}];

//这是我要添加的内容

people = {
  name: 'joe',
  year: 1992
}

//我希望它表现得像

people = [{
  name: 'robert',
  year: 1993
}, {
  name: 'joe',
  year: 1992
}];

我希望能够使用 人[0].姓名

【问题讨论】:

  • 这是打字稿,请致电Person 了解它们的含义。 people as {}[]people as {} 令人困惑。 people 的单数是 Person 所以试试 Person[] 其中Person 是一个定义明确的类型。
  • "如何在 Typescript 中向基于 json 的对象添加更多数据?" -- 通过扩展或组合。

标签: javascript json angular typescript


【解决方案1】:

假设您希望people 变量是一个对象数组,

const people = [{ name: 'robert', year: 1993 }];

如果你想给people添加一个对象,

const newPerson = { name: 'joe', year: 1992 };
people.push(newPerson);

如果您想访问单个对象/属性,

people[0];
people[0]['name'];

关于您的后续问题,您可能需要提供people 的类型定义。

export class AppComponents { 
  // your properties and methods
}

interface Person {
  name: string;
  year: number; 
}

在您的主代码本身上,您可以使用类型声明变量。

const people: Person[] = [{ name: 'robert', year: 1993 }];
const newPerson: Person = { name: 'joe', year: 1992 };
people.push(newPerson);

【讨论】:

  • 我添加了这个并得到一个错误,说后续属性声明必须具有相同的类型。属性 'people' 的类型必须是 '{name: string;年份:数字; } [ ] ' ,但这里有类型 'any' 。 ts (2717)
  • @RobertoMejia 我明白了.. 嗯,我已经更新了我的代码以包含接口,以便我们可以使用它来为我们的对象/数组提供类型定义。让我知道它是否解决了问题?
  • 当我放置界面时,它给了我一个错误,说 Unexpected token。需要构造函数、方法、访问器或属性。
  • Ok ermm.. 你把接口放在哪里了
  • 我把它放在 AppComponent 类中,所以在我拥有的类中,接口和你给我的最后 3 行代码开头,const people: Person[], const newPerson:人和people.push
【解决方案2】:

试试这个

people.push({ name: 'joe', year: 1992 });

【讨论】:

  • 我添加了这个并得到一个错误,说后续属性声明必须具有相同的类型。属性 'people' 必须是 '{name: string;年份:数字; } [ ] ' ,但这里有类型 'any' 。 ts (2717)
  • 确保你推的人有准确的类型。
  • 是的,正如你所拥有的一样,我试过了,它给了我这个错误
  • 你能在这里分享个人类代码以及你也在推动什么吗?
  • 从'@angular/core'导入{组件}; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) 导出类 AppComponent { title = 'hi'; people = [{ name: 'robert', year: 1993 }]; people.push({ name: 'joe', year: 1992 });
猜你喜欢
  • 2018-12-01
  • 1970-01-01
  • 2013-09-05
  • 1970-01-01
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
  • 2019-07-10
  • 1970-01-01
相关资源
最近更新 更多