Home > Net >  How to iterate object when it contains array of objects?
How to iterate object when it contains array of objects?

Time:04-20

Input :

{
    "id": "123",
    "address": [{
        "street": "5",
        "city": "ameerpet",
        "pin": "500073"
    }, {
        "street": "6",
        "city": "sec",
        "pin": "500020"
    }]
}

Note: ["LAA001","LAA002","LAA003"] -> use this as a variable

Required output:

[{
        "id": "123",
        "lob": "LAA001",
        "attributeText": "5"
    },
    {
        "id": "123",
        "lob": "LAA001",
        "attributeText": "6"
    },
    {
        "id": "123",
        "lob": "LAA002",
        "attributeText": "ameerpet"
    },
    {
        "id": "123",
        "lob": "LAA002",
        "attributeText": "sec"
    },
    {
        "id": "123",
        "lob": "LAA003",
        "attributeText": "500073"
    },
    {
        "id": "123",
        "lob": "LAA003",
        "attributeText": "500020"
    }
]

CodePudding user response:

If you are using JavaScript, that should work:

var input = { "id": "123", "address": [ { "street": "5", "city": "ameerpet", "pin": "500073" }, { "street": "6", "city": "sec", "pin": "500020" }] }
    var iob = ["LAA001","LAA002","LAA003"]
    var output = []
    
    input['address'].forEach((item, index) => {
      var keyIndex = 0 
      for(const key in item){
        let obj = {
          "id": input['id'],
          "lob": iob[keyIndex],
          "attributeText": item[key]
        }
        output.push(obj)
        keyIndex  = 1
    }

CodePudding user response:

%dw 2.0
output application/json
var inp = ["LAA001","LAA002","LAA003"]
var inp1 = payload.address.street    payload.address.city    payload.address.pin
---
inp1 map {
   id: payload.id,
   lob: inp[(($$)/2)],
   attributeText: $
}
  • Related