我要做的是只从JSON中提取数据,而不是头文件(例如,获取1而不提取ID或获取foo而不提取名称)。
[{ID = 1, Name = "foo", Email = "foo@foo.com"},
{ID = 2, Name = "bar", Email = "bar@bar.com"}]我只想要数据而不是头的原因是数据可以是动态的。在一次调用中,返回的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数据分成几部分传递给接口,同时区分可能在同一对象中的不同行?
发布于 2017-07-06 22:37:34
ES6方式:这将为您提供一个array,其中每个object包含1个array,这是您最初拥有的。每个子数组将只是这些对象的值。
JSON.parse(dataCarrier).map(Object.values)因此,在您的示例中,它将导致:
[{ID = 1, Name = "foo", Email = "foo@foo.com"},
{ID = 2, Name = "bar", Email = "bar@bar.com"}]
// =>
[[1, "foo", "foo@foo.com"], [2, "bar", "bar@bar.com"]]有关Object.values的更多信息,请访问:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Object/values
如果你不能使用ES6,你可以用ES5和Object.keys来做。代码将更加冗长,但它可以完成工作:
JSON.parse(dataCarrier).map(function(obj) {
return Object.keys(obj).map(function (key) {
return obj[key];
});
});*改编自How to get all properties values of a Javascript Object (without knowing the keys)?
https://stackoverflow.com/questions/44951880
复制相似问题