将 JSON 数组粘贴到打字稿数组中
Posted
技术标签:
【中文标题】将 JSON 数组粘贴到打字稿数组中【英文标题】:Pasting array of JSON into typescript array 【发布时间】:2017-09-23 01:30:02 【问题描述】:我有一个 JSON 数组,想将它粘贴到 typescript 中的数组变量中。
我从http://www.example.com/select.php 收到的 JSON:
"User":[
"Name":"Luca M","ID":"1",
"Name":"Tim S","ID":"2",
"Name":"Lucas W","ID":"3"
]
我想要一个这样的数组:
this.items = [
'Luca M',
'Tim S',
'Lucas W'
];
编辑:
当前代码是
this.http.post('http://www.example.com/select.php', creds,
headers: headers
)
.map(res => res.json().User)
.subscribe(
data => this.data = data.User.map(user => user.Name),
err => this.logError(err),
() => console.log('Completed')
);
this.items = this.data;
错误:
无法读取未定义的属性“地图”
我怎样才能意识到这一点?
感谢和问候
【问题讨论】:
【参考方案1】:对于这个非常具体的 json:
const json =
"User": [
"Name": "Luca M", "ID": "1" ,
"Name": "Tim S", "ID": "2" ,
"Name": "Lucas W", "ID": "3"
]
const items = json.User.map(user => user.Name);
console.log(items); // ["Luca M", "Tim S", "Lucas W"]
(code in playground)
【讨论】:
感谢您的建议,我忘了提及,我从 API 接收我的 JSON。你能根据我的编辑再帮我一次吗? 我试过 const json = JSON.stringify(this.data); this.items = this.data.map(user => user.Name);但这并没有像我预期的那样工作 你不需要stringify
你的数据,如果你这样做,你最终会得到一个字符串而不是一个对象......
好吧,有道理,但它也不起作用 this.items = this.data.map(User => User.Name); --无法读取未定义的属性“地图”
您可能正在执行异步操作。您需要等到完成。在subscribe
回调中执行该部分:data => this.data = data.User.map(user => user.Name)
以上是关于将 JSON 数组粘贴到打字稿数组中的主要内容,如果未能解决你的问题,请参考以下文章