Prajakta
Prajakta

Reputation: 39

How to add/insert element in array one after another like stack swift 5

I get String from api response and stored in an array.

     for customParams in custom_attributes! {
         if(customParams["attribute_code"] as! String == "small_image") 
        {
         print(customParams["value"])
         var myString = customParams["value"] as! String

         //want to add this myString in array(myArray) one after another
         var myArray :[String] = []
              print(myArray)      
        }
 }

Output:

myArray = ["myString1","myString2"......]

How do I do it guys? I'm still new to swift... Thanks in advance!

"id": 6,
"products": {
"items": [{
"status": 1,
"custom_attributes": [
{
{
"attribute_code": "small_image",
"value": "small_image"
},
{
"attribute_code": "meta_keyword",
"value": "meta_keyword"
}]},
{
"status": 1,
"custom_attributes": [
{
{
"attribute_code": "small_image",
"value": "small_image"
},
{
"attribute_code": "meta_keyword",
"value": "meta_keyword"
}
]}]}}]

want to fetch customParams["attribute_code"] == small_image

Upvotes: 1

Views: 611

Answers (2)

Lokesh gupta
Lokesh gupta

Reputation: 94

var myArray :[String] = []

for customParams in custom_attributes! {    
    if(customParams["attribute_code"] as! String == "small_image") {
         var myString = customParams["value"] as! String
         myArray.append(myString)
    }
}

Upvotes: 0

Mumtaz Hussain
Mumtaz Hussain

Reputation: 1125

You need to loop through the items array first as it is in json, also declare myArray outside the for loop and start appending myString inside myArray as shown:

var myArray :[String] = []
for custom_attributes! in items { // items is the json items array
    for customParams in custom_attributes! {
        if(customParams["attribute_code"] as! String == "small_image") 
             {
             print(customParams["value"])
             var myString = customParams["value"] as! String
             myArray.append(myString)

         }
     }
 }

Upvotes: 1

Related Questions