简体   繁体   中英

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.

JSON Format:

{
     "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

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. Is there something which I am missing out maybe. The code is a typescript file with the name as dashboard.component.ts

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. 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

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

the second way works because you're just constructing a new array with 1 item.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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