cancel
Showing results for 
Search instead for 
Did you mean: 

How to split JSON based on Key using xsjs?

former_member594414
Participant
0 Kudos

Hi, below is the JSON object I have {"Name":"John", "Name-Second":"Martin"}

I need some 2 JSON objects based on the Key (using string values) i.e

I want to get Name-Second as a different JSON object. How to do this?

JSON 1: {"Name":"John"}

JSON 2: {"Name-Second":"Martin"}

View Entire Topic
pfefferf
Active Contributor

There are a lot of different ways to that. One example would be to create for each property within your original object a new object. In the following example this is done; the new objects are stored in array newObjects.

let obj = {"Name":"John", "Name-Second":"Martin"};

let newObjects = [];

for(let prop in obj) {
    if(obj.hasOwnProperty(prop)){
        let newObj = {};
        newObj[prop] = obj[prop];
        newObjects.push(newObj);
    }
}

former_member594414
Participant
0 Kudos

Hi Florian, thanks for the response. Let me get to the exact JSON format. The JSON looks like below

{"Name":"John", "Name-Second":"Martin", "Location" : "US", "Location-Second" : "India"};

I need the output as below

JSON 1 : {"Name":"John", "Location" : "US"}
JSON 2 : {"Name-Second":"Martin" , "Location-Second" : "India"}

The split should be based on the string "-" instead of the property. How to split in this case?
pfefferf
Active Contributor
0 Kudos

Are the property names "Name", "Name-Second", "Location" and "Location-Second" fix or are they somehow flexible? And are there additional properties instead of these ones you described now (aka is that what you are telling us now the whole truth)?

former_member594414
Participant
0 Kudos

Yes, this is the whole JSON which I want to split. There are no additional properties involved. My bad, I didn't mention this clearly.