【问题标题】:Extracting just JSON data, not the headers, to a string array with typescript仅将 JSON 数据而不是标头提取到带有 typescript 的字符串数组
【发布时间】:2017-12-10 15:16:36
【问题描述】:

我要做的是仅从 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 数据分解成几部分以传递到接口,同时区分同一对象中可能存在的不同行?

【问题讨论】:

    标签: javascript arrays json angular typescript


    【解决方案1】:

    ES6 方式:这将为您提供一个 array,其中包含 1 个 array 每个 object,您最初拥有的。每个子数组将只是这些对象的值。

    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,您可以使用ES5Object.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)?

    【讨论】:

    • 当我尝试使用此代码时,它会在 Object.values 上引发错误。它说“'ObjectConstructor'类型上不存在属性'值'
    • 代码应该可以正常运行:jsfiddle.net/vdvjj72d 如果您使用的是TypeScript,您可以将目标更改为ES6target: 'es6' in tsconfig.json。如果这不是一个选项,请告诉我,我会发布 ES5 版本,它会更长一点。或者,如果您已经在使用 lodashunderscore,则可以将 Object.values 替换为 _.values
    • 这可能不是一个选项。该项目是一个带有 Angular 的 .NET Core 项目,它制作了一些 tsconfig 文件。如果您也可以发布 es5 版本,我将不胜感激
    • @Joris,添加了ES5 版本,这是更新后的小提琴:jsfiddle.net/vdvjj72d/1
    猜你喜欢
    • 2014-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    相关资源
    最近更新 更多