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

Accepted Solutions (1)

Accepted Solutions (1)

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.

Answers (1)

Answers (1)

pfefferf
Active Contributor
0 Kudos

According to your comments to my first answer you have more properties, but they are fix. With that you can do for instance following simple approach:

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

let obj1 = {};
obj1["Name"] = obj["Name"];
obj1["Location"] = obj["Location"];

let obj2 = {};
obj2["Name-Second"] = obj["Name-Second"];
obj2["Location-Second"] = obj["Location-Second"];