简体   繁体   English

typescript Angular 中的阵列问题

[英]Array issue in typescript Angular

I am coding an angular application and I am facing an issue with storing an API object data into an array of strings.我正在编写一个 angular 应用程序,我遇到了将 API object 数据存储到字符串数组中的问题。

JSON Format: JSON 格式:

{
     "data1":{
     "data11":"data11d",
     "statename":"West Bengal"
     },
     "data2":{
         "data21":"data21d",
     "statename":"Assam"
     }
 }

I am using '.values' with a index to pull out the inside statename value of the first key data1 through code and storing it in an array of string to index 0 with the code我正在使用带有索引的“.values”通过代码提取第一个键 data1 的内部 statename 值,并将其存储在字符串数组中以使用代码索引 0

this.myObj=Object.values(this.apiJson)[0]; //Obj data is coming which is debugged and checked
this.myStringArray[0]=this.myObj["statename"];

But the value is not coming into the array but when I use another way of declaration of the string array it works但是该值没有进入数组但是当我使用另一种声明字符串数组的方式时它可以工作

this.myObj=Object.values(this.apiJson)[0]; //Obj data is coming which is debugged and checked
this.myStringArray=[this.myObj["statename"]];

the Output should be West Bengal which is coming in the 2nd coding way but not the first. Output 应该是西孟加拉邦,它以第二种编码方式出现,但不是第一种。 Is there something which I am missing out maybe.有什么我可能错过的东西。 The code is a typescript file with the name as dashboard.component.ts代码是一个名为dashboard.component.ts的typescript文件

But the second way Cannot be used in a loop to make a big array of string但是第二种方式不能在循环中使用来制作一个大的字符串数组

Thanks anyway as this community has helped me a lot.无论如何,谢谢,因为这个社区对我帮助很大。 Please mention if any more details are required I would provide that as well.请提及是否需要更多详细信息,我也会提供。

I'm assuming myStringArray is an empty array, and the first way isn't how you add items to an array.我假设myStringArray是一个空数组,第一种方法不是如何将项目添加到数组中。 it's how you replace an item in an array at an index that already exists... if you want to add an item to the end, do this:这是您如何替换数组中已经存在的索引处的项目...如果您想在末尾添加一个项目,请执行以下操作:

this.myStringArray.push(this.myObj["statename"]);

if you want to add it to the start use shift如果你想将它添加到开始使用shift

this.myStringArray.shift(this.myObj["statename"]);

the second way works because you're just constructing a new array with 1 item.第二种方法有效,因为您只是在构建一个包含 1 个项目的新数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM