on 01-08-2019 9:41 AM
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"}
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);
}
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
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?
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"];
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
88 | |
10 | |
10 | |
9 | |
6 | |
6 | |
6 | |
5 | |
4 | |
3 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.