我要做的是从JSON中提取数据而不是 Headers (例如,获取1而不是ID或获取foo而不是Name)
[{ID = 1, Name = "foo", Email = "foo@foo.com"},
{ID = 2, Name = "bar", Email = "bar@bar.com"}]
我只想要数据而不是 Headers 的原因是数据可以是动态的 . 在一次调用中,返回的JSON可以在每个对象上有100个字段,或者在下一次调用时每个对象有2个字段 . 这就是为什么,在下面的例子中,我的界面中只有一个字符串,因为我不知道可以传递什么样的数据 .
这是我试图解释数据的打字稿
import { Component } from '@angular/core';
import { Http } from '@angular/http';
@Component({
selector: 'fetchdata',
template: require('./fetchdata.component.html')
})
export class FetchDataComponent {
public rowData: RowInfo[];
constructor(http: Http) {
http.get('/api/SampleData/DatatableData').subscribe(result => {
//This is where the magic should happen
//This currently does not work
var dataCarrier = result.toString();
JSON.parse(dataCarrier).forEach(item => {
this.rowData = item.name;
});
});
}
}
interface RowInfo {
rowData: string;
}
我如何将http.get中的JSON数据分解为其中的部分以传递到接口,同时区分可能位于同一对象中的不同行?
1 回答
ES6方式:这将给你一个
array
,包括你原来拥有的array
每object
. 每个子数组只是这些对象的值 .所以在你的例子中它会导致:
有关
Object.values
的更多信息:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Object/values如果您不能使用
ES6
,则可以使用ES5
和Object.keys
进行操作 . 代码将更加冗长,但它完成了工作:*改编自How to get all properties values of a Javascript Object (without knowing the keys)?