Skip to Content

How to split JSON based on Key using xsjs?

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

Add comment
10|10000 characters needed characters exceeded

  • Follow
  • Get RSS Feed

2 Answers

  • Best Answer
    Jan 08 at 11:50 AM

    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);
        }
    }
    
    
    Add comment
    10|10000 characters needed characters exceeded

  • Jan 10 at 08:52 AM

    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"];
    
    Add comment
    10|10000 characters needed characters exceeded