1

I have a json in the following format, I want to convert this JSON into the format mentioned at the end of the question. I want to use only javascript to do this conversion and not any other tools like Gson or service side Java code. Please let me know how this can be achieved.

 [{
    "innNumber": {
        "id": "0111",
        "idAsLong": 111,
        "idWithoutZero": "111"
    },
    "nightlyRates": [{
        "date": "2017-02-09",
        "nightlyRate": {
            "amount": 155.85,
            "currencyCode": "CAD"
        },
        "points": 0
    }]
}, {
    "innNumber": {
        "id": "0111",
        "idAsLong": 111,
        "idWithoutZero": "111"
    },
    "nightlyRates": [{
        "date": "2017-02-09",
        "nightlyRate": {
            "amount": 155.85,
            "currencyCode": "CAD"
        },
        "points": 0
    }]

}]

JSON Response that is to be in the following required format.

    [{"hotelRoomRate":{
    "innNumber": {
        "id": "0111",
        "idAsLong": 111,
        "idWithoutZero": "111"
    },
    "nightlyRates": [{
        "date": "2017-02-09",
        "nightlyRate": {
            "amount": 155.85,
            "currencyCode": "CAD"
        },
        "points": 0
    }]

  } 
}, 
{"hotelRoomRate":
  {
    "innNumber": {
        "id": "0111",
        "idAsLong": 111,
        "idWithoutZero": "111"
    },
    "nightlyRates": [{
        "date": "2017-02-09",
        "nightlyRate": {
            "amount": 155.85,
            "currencyCode": "CAD"
        },
        "points": 0
    }]

}   
}]
1

2 Answers 2

3

A simple map() will do it

var res = data.map(function(item){
   return { hotelRoomRate : item};
});
Sign up to request clarification or add additional context in comments.

Comments

0

This is how I would do it...

    var JsonData = [{
        "innNumber": {
            "id": "0111",
            "idAsLong": 111,
            "idWithoutZero": "111"
        },
        "nightlyRates": [{
            "date": "2017-02-09",
            "nightlyRate": {
                "amount": 155.85,
                "currencyCode": "CAD"
            },
            "points": 0
        }]
    }, {
        "innNumber": {
            "id": "0111",
            "idAsLong": 111,
            "idWithoutZero": "111"
        },
        "nightlyRates": [{
            "date": "2017-02-09",
            "nightlyRate": {
                "amount": 155.85,
                "currencyCode": "CAD"
            },
            "points": 0
        }]

    }]

var newFormat = [];

for(var i =0; i < JsonData.length; i ++){
   newFormat.push({"hotelRoomRate" : JsonData[i]})
}

console.log(newFormat)

Hope this helps

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.