Original json data:
{
"UniversalOne": "",
"CommonOne": "",
"Implementations": [
{
"BirthDate": "",
"UniqueTraits": "",
"Male": {
"Gender": "Male",
"PlaceOfBirth": "",
"Weight": "",
"Height": "",
"EyeColor": ""
},
"Female": {
"Gender": "Female",
"PlaceOfBirth": "",
"Weight": "",
"Height": "",
"EyeColor": ""
},
"Country": [
{
"Orientation": "Male",
"Name": "ABCD",
"County": "East"
},
{
"Orientation": "Male",
"Name": "ABCD",
"County": "West"
},
{
"Orientation": "Female",
"Name": "EFGH",
"County": "East"
},
{
"Orientation": "Female",
"Name": "EFGH",
"County": "West"
},
{
"Orientation": "Female",
"Name": "IJKL"
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
],
"Boy": [
{
"AgeGroup": "A",
"Id": 1,
"MaternalName": "",
"PaternalName": ""
},
{
"AgeGroup": "B",
"Id": 2,
"MaternalName": "",
"PaternalName": ""
},
{
"AgeGroup": "C",
"Id": 3,
"MaternalName": "",
"PaternalName": ""
}
]
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {},
"UniversalThree": "",
"CommonThree": ""
}
Expected json response:
{
"UniversalOne": "",
"CommonOne": "",
"Implementations": [
{
"BirthDate": "",
"UniqueTraits": "",
"Male": {
"Gender": "Male",
"PlaceOfBirth": "",
"Weight": "",
"Height": "",
"EyeColor": "",
"Country": [
{
"Orientation": "Male",
"Name": "ABCD"
}
],
"EastCounty": {
"Orientation": "Male",
"Name": "ABCD",
"County": "East"
},
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
},
"Female": {
"Gender": "Female",
"PlaceOfBirth": "",
"Weight": "",
"Height": "",
"EyeColor": "",
"Country": [
{
"Orientation": "Female",
"Name": "EFGH"
},
{
"Orientation": "Female",
"Name": "IJKL"
}
],
"EastCounty": {
"Orientation": "Female",
"Name": "EFGH",
"County": "East"
},
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
},
"Girl": [
{
"AgeGroup": "A",
"identification": [
{
"Number": 1,
"MaternalName": "",
"PaternalName": ""
}
]
},
{
"AgeGroup": "B",
"identification": [
{
"Number": 1,
"MaternalName": "",
"PaternalName": ""
}
]
},
{
"AgeGroup": "C",
"identification": [
{
"Number": 1,
"MaternalName": "",
"PaternalName": ""
}
]
}
]
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {},
"UniversalThree": "",
"CommonThree": ""
}
Questions:
I have three specific questions:
1) How do I retain the attributes that are directly under "Male" and "Female" and also before "Male"? After I run my program these attributes are not shown in my response.
I want to retain attributes like
"BirthDate":"",
"UniqueTraits": "" AND
"Gender": "Male",
"PlaceOfBirth": "",
"Weight": "",
"Height": "",
"EyeColor": ""
exactly as in my original and expected json data.
2) How do I add another EastCounty{} after Country[] both in Male and Female based on "County": East and Orientation? Please refer the original and expected json for reference.
3) How do I restructure Boy[] in original json to the new structure exactly as is shown in Girl[] in expected json response? Note "Id" in Boy[] changes to "Number" in Girl.So if there are multiple "identification" in either of the "AgeGroup" then "Number" would change sequentially for every record.
Current program:
function modifyImplementations(Implementations) {
var finalResult = [];
for (var i = 0; i < Implementations.Implementations.length; i++) {
var currentImplementation = Implementations.Implementations[i];
var targetObj = {
"Male": {
"Gender": "Male",
"Country": [],
"State": currentImplementation.State
},
"Female": {
"Gender": "Female",
"Country": [],
"State": currentImplementation.State
}
};
for (var j = 0; j < currentImplementation.Country.length; j++) {
var currentCountry = currentImplementation.Country[j];
if (currentCountry.Orientation === 'Male') {
targetObj.Male.Country.push(currentCountry);
} else if (currentCountry.Orientation === 'Female') {
targetObj.Female.Country.push(currentCountry);
}
}
finalResult.push(targetObj);
}
return finalResult
}
var x = Object.assign({}, Implementations);
x.Implementations = modifyImplementations(Implementations);
console.log(JSON.stringify(x));
This should be working function which would produce expected result, Please do some refactoring as certainly there are better ways to implement in few areas of code, just quickly done all your needs here to produce expected o/p and also your question needs to be updated with valid JSON's :
function modifyImplementations(Implementations) {
for (let i = 0; i < Implementations.Implementations.length; i++) {
let currentImplementation = Implementations.Implementations[i];
currentImplementation['Male']['Country'] = []
currentImplementation['Female']['Country'] = []
currentImplementation['Male']['EastCounty'] = []
currentImplementation['Female']['EastCounty'] = []
currentImplementation['Male']['State'] = currentImplementation['State'];
currentImplementation['Female']['State'] = currentImplementation['State'];
for (let j = 0; j < currentImplementation.Country.length; j++) {
let currentCountry = currentImplementation.Country[j];
let currentCountryObj = {}
if (currentCountry.Orientation === 'Male') {
if (currentCountry.County && currentCountry.County == "East") {
currentCountryObj['County'] = currentCountry.County
currentCountryObj['Name'] = currentCountry.Name
currentCountryObj['Orientation'] = currentCountry.Orientation
currentImplementation['Male']['EastCounty'].push(currentCountryObj)
} else {
currentCountryObj['Name'] = currentCountry.Name
currentCountryObj['Orientation'] = currentCountry.Orientation
currentImplementation['Male']['Country'].push(currentCountryObj);
}
} else if (currentCountry.Orientation === 'Female') {
if (currentCountry.County && currentCountry.County == "East") {
currentCountryObj['County'] = currentCountry.County
currentCountryObj['Name'] = currentCountry.Name
currentCountryObj['Orientation'] = currentCountry.Orientation
currentImplementation['Female']['EastCounty'].push(currentCountryObj)
} else {
currentCountryObj['Name'] = currentCountry.Name
currentCountryObj['Orientation'] = currentCountry.Orientation
currentImplementation['Female']['Country'].push(currentCountryObj);
}
}
}
delete currentImplementation['Country']
delete currentImplementation['State']
let mapObj = [];
for (items of currentImplementation.Boy) {
let objs = currentImplementation.Boy.filter((obj) => {
return items.AgeGroup === obj.AgeGroup
})
mapObj.push(objs)
currentImplementation.Boy = currentImplementation.Boy.filter(e => e.AgeGroup !== items.AgeGroup);
}
let finalArray = mapObj.filter(e => e.length > 0)
currentImplementation['Girl'] = []
for (anArray of finalArray) {
let finalObj = {}
finalObj.identification = [];
if (anArray.length && anArray.length > 1) {
let number = 1
for (oneObj of anArray) {
let objs = {};
objs['Number'] = number
objs['MaternalName'] = oneObj['MaternalName']
objs['PaternalName'] = oneObj['PaternalName']
number += 1
finalObj['AgeGroup'] = oneObj.AgeGroup
finalObj.identification.push(objs);
}
} else if (anArray.length == 1) {
let objs = {};
finalObj['AgeGroup'] = anArray[0].AgeGroup
objs = {};
objs['Number'] = 1
objs['MaternalName'] = anArray[0]['MaternalName']
objs['PaternalName'] = anArray[0]['PaternalName']
finalObj.identification.push(objs);
}
currentImplementation['Girl'].push(finalObj)
delete currentImplementation['Boy']
}
}
return Implementations
}
Related
The Object returns users data with test results (pass, fail or Not-taken) based on their places. Trying to convert below object to something like this.
1st request
place_A
totalUsers = 2,pass = 1 (50%),fail = 1(50%), NotTaken = 0(0%)
place_B
totalUsers = 3,pass = 1(33.3%),fail = 1(33.3%), NotTaken = 1(33.3%)
others
totalUsers = 1,pass = 1(100%),fail = 0(0%), NotTaken = 0(0%)
2nd Request (can someone help to get this.)
place_A
totalUsers = 2,pass = 1 (50%),fail = 1(50%), NotTaken = 0(0%), name = place_A, items = objects(data of 2 users)
place_B
totalUsers = 3,pass = 1(33.3%),fail = 1(33.3%), NotTaken = 1(33.3%), name = place_B, items = objects(data of 3 users)
others
totalUsers = 1,pass = 1(100%),fail = 0(0%), NotTaken = 0(0%), name = others, items = objects(data of 1 user)
{
"place_A": [
{
"employeeId": "1",
"department": "A",
"place": "place_A",
"status": "Pass",
"score": 12
},
{
"employeeId": "10",
"department": "B",
"place": "place_A",
"status": "Fail",
"score": 02
}
],
"place_B": [
{
"employeeId": "2",
"department": "place_B_Dept_A",
"place": "place_B",
"status": "Pass",
"score": 20
},
{
"employeeId": "3",
"department": "place_B_Dept_B",
"place": "place_B",
"status": "fail",
"score": 05
},
{
"employeeId": "4",
"department": "place_B_Dept_B",
"place": "place_B",
"status": "",
"score": 0
}
],
"": [
{
"employeeId": "6",
"department": "someOtherDept",
"place": null,
"status": "Pass",
"score": 20,
}
]
}
I tried to make changes to the result of #decpk by adding items and name but only the first item is being added not all. Help please.
const temp = { totalUsers: 0, pass: 0, fail: 0, notTaken: 0, items :{}, name:""}
obj[curr].forEach(obj => {
temp.name = obj.place;
temp.items = obj;
})
You can easily achive this result using reduce and forEach.
const obj = {
"place_A": [
{
"employeeId": "1",
"department": "A",
"place": "place_A",
"status": "Pass",
"score": 12
},
{
"employeeId": "10",
"department": "B",
"place": "place_A",
"status": "Fail",
"score": 02
}
],
"place_B": [
{
"employeeId": "2",
"department": "place_B_Dept_A",
"place": "place_B",
"status": "Pass",
"score": 20
},
{
"employeeId": "3",
"department": "place_B_Dept_B",
"place": "place_B",
"status": "fail",
"score": 05
},
{
"employeeId": "4",
"department": "place_B_Dept_B",
"place": "place_B",
"status": "",
"score": 0
}
],
"": [
{
"employeeId": "6",
"department": "someOtherDept",
"place": null,
"status": "Pass",
"score": 20,
}
]
}
const result = Object.keys(obj).reduce((acc, curr) => {
const temp = { totalUsers: 0, pass: 0, fail: 0, notTaken: 0}
obj[curr].forEach(obj => {
temp.totalUsers += 1;
temp[obj.status.toLowerCase() || "notTaken"] += 1;
})
acc[curr || "others"] = temp;
return acc;
}, {});
console.log(result);
I've got the following JSON:
var obj =
{
"workers": [
{
"TimeStamp": "2020-03-13T10:08",
"Status": "status1",
"Name": "one",
"Number": 19.9
},
{
"TimeStamp": "2019-07-19T06:01",
"Status": "status2",
"Name": "one",
"Number": 9
},
{
"TimeStamp": "2020-04-22T05:10",
"Status": "status2",
"Name": "one",
"Number": 10.1
},
{
"TimeStamp": "2019-07-21T23:53",
"Status": "status2",
"Name": "two",
"Number": 16.3
},
{
"TimeStamp": "2019-11-21T05:14",
"Status": "status1",
"Name": "three",
"Number": 122.54
},
...
]
};
As you see there's just 2 different status possible: "status1" and "status2".
Names should be filtered to be shown just once, but combine the two different status.
The respective status should include the "TimeStamp" and "Number" in an array.
In the end it should look like this:
{
"workers": [
{
"Name":"one",
"status1": [
{
"TimeStamp":"2020-03-13T10:08",
"Number": 19.9
}
],
"status2": [
{
"TimeStamp":"2019-07-19T06:01",
"Number": 9
},
{
"TimeStamp": "2020-04-22T05:10",
"Number": 10.1
},
]
},
{
"Name":"two",
"status1": [],
"status2": [
{
"TimeStamp":"2019-07-21T23:53",
"Number": 16.3
}
]
},
{
"Name":"three",
"status1": [
{
"TimeStamp":"2019-11-21T05:14",
"Number": 122.54
}
],
"status2": []
}
]
}
I tried out the following so far:
var writeObj = { 'workers': [] };
for (var i = 0; i < obj.workers.length; i++) {
if(!Object.values(writeObj.workers).includes(obj.workers[i].Name)) {
writeObj['workers'].push({ Name: obj.workers[i].Name, 'status1': [], 'status2': [] });
for (var j = 0; j < obj.workers.length; j++) {
if (obj.workers[j].Name === obj.workers[i].Name && obj.workers[j].Status === 'status1') {
writeObj['workers'][i]['status1'].push({ TimeStamp: obj.workers[j].TimeStamp, Number: obj.workers[j].Number });
} else if (obj.workers[j].Name === obj.workers[i].Name && obj.workers[j].Status === 'status2') {
writeObj['workers'][i]['status2'].push({ TimeStamp: obj.workers[j].TimeStamp, Number: obj.workers[j].Number });
}
}
}
}
I'm stuck and can't see the mistake...
Thanks for any help!
You can aggregate your data using array.reduce:
var obj =
{
"workers": [
{
"TimeStamp": "2020-03-13T10:08",
"Status": "status1",
"Name": "one",
"Number": 19.9
},
{
"TimeStamp": "2019-07-19T06:01",
"Status": "status2",
"Name": "one",
"Number": 9
},
{
"TimeStamp": "2020-04-22T05:10",
"Status": "status2",
"Name": "one",
"Number": 10.1
},
{
"TimeStamp": "2019-07-21T23:53",
"Status": "status2",
"Name": "two",
"Number": 16.3
},
{
"TimeStamp": "2019-11-21T05:14",
"Status": "status1",
"Name": "three",
"Number": 122.54
}
]
};
let output = obj.workers.reduce((acc,cur) => {
let {Name, Status, ...rest} = cur;
let match = acc.find(x => x.Name === Name);
if(!match){
match = { Name: Name };
acc.push(match);
}
if(!match[Status]){
match[Status] = [];
}
match[Status].push(rest);
return acc;
}, []);
console.log({workers: output});
You can use Array#reduce. Group by the Name key according to your format, then take the grouped values as the result. Time complexity is O(n).
var obj = { "workers": [ { "TimeStamp": "2020-03-13T10:08", "Status": "status1", "Name": "one", "Number": 19.9 }, { "TimeStamp": "2019-07-19T06:01", "Status": "status2", "Name": "one", "Number": 9 }, { "TimeStamp": "2020-04-22T05:10", "Status": "status2", "Name": "one", "Number": 10.1 }, { "TimeStamp": "2019-07-21T23:53", "Status": "status2", "Name": "two", "Number": 16.3 }, { "TimeStamp": "2019-11-21T05:14", "Status": "status1", "Name": "three", "Number": 122.54 }, ] };
const grouped = Object.values(obj.workers.reduce((a, e) => {
if (!a[e.Name]) {
a[e.Name] = {Name: e.Name, status1: [], status2: []};
}
a[e.Name][e.Status].push({TimeStamp: e.TimeStamp, Number: e.Number});
return a;
}, {}));
console.log(grouped);
Original json data:
{
"UniversalOne": "",
"CommonOne": ""
"Implementations": [
{
"Male": {
"Gender": "Male"
},
"Female": {
"Gender": "Female"
},
"Country": [
{
"Orientation": "Male",
"Name": ABCD
},
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
Expected json data:
{
"UniversalOne": "",
"CommonOne": ""
"Implementations": [
{
"Male": {
"Gender": "Male"
"Country": [
{
"Orientation": "Male",
"Name": ABCD
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
},
"Female": {
"Gender": "Female"
"Country": [
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
Program:
//Original JSON data in question.
var Implementations = {
"UniversalOne": "",
"CommonOne": ""
"Implementations": [
{
"Male": {
"Gender": "Male"
},
"Female": {
"Gender": "Female"
},
"Country": [
{
"Orientation": "Male",
"Name": ABCD
},
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
// Program that make the conversion
var finalResult = [];
for (var i=0; i<Implementations.Implementations.length; i++) {
var currentImplementation = Implementations.Implementations[i];
var targetObj = {
"Male": {
"Gender": "Male",
"Country": [],
"State": currentImplementation.State
},
"Female": {
"Gender": "Female",
"Country": [],
"State": currentImplementation.State
}
};
for (var j=0; j<currentImplementation.Country.length; j++) {
var currentCountry = currentImplementation.Country[j];
if (currentCountry.Orientation === 'Male') {
targetObj.Male.Country.push(currentCountry);
} else if (currentCountry.Orientation === 'Female') {
targetObj.Female.Country.push(currentCountry);
}
}
finalResult.push(targetObj);
}
console.log(JSON.stringify(finalResult));
How do I add the objects like Personality Traits, Eating Habits, Reading Habits, Fitness Habits and attributes like Universal and common outside of the Implementations object as shown in the expected json data?
The easiest way would be using Object.assign to merge the attributes.
//The Original Data
const Implementations = {
"Implementations": [
{
//Ignore
}
]
}
//The Attributes needed
const attributes = {
"UniversalOne": "",
"CommonOne": "",
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
const newData = Object.assign({}, Implementations, attributes);
console.dir(newData);
OR just add the data inside.
const Implementations = {
"Implementations": [
{
//Ignore
}
]
}
const newData = {
"UniversalOne": "",
"CommonOne": "",
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
newData.Implementations = Implementations.Implementations;
console.dir(newData);
Original json data:
{
"UniversalOne": "",
"CommonOne": ""
"Implementations": [
{
"Male": {
"Gender": "Male"
},
"Female": {
"Gender": "Female"
},
"Country": [
{
"Orientation": "Male",
"Name": ABCD
},
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
Expected json data:
{
"UniversalOne": "",
"CommonOne": ""
"Implementations": [
{
"Male": {
"Gender": "Male"
"Country": [
{
"Orientation": "Male",
"Name": ABCD
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
},
"Female": {
"Gender": "Female"
"Country": [
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
Program:
//Original JSON data in question.
var Implementations = {
"UniversalOne": "",
"CommonOne": ""
"Implementations": [
{
"Male": {
"Gender": "Male"
},
"Female": {
"Gender": "Female"
},
"Country": [
{
"Orientation": "Male",
"Name": ABCD
},
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
// Program that make the conversion
var finalResult = [];
for (var i=0; i<Implementations.Implementations.length; i++) {
var currentImplementation = Implementations.Implementations[i];
var targetObj = {
"Male": {
"Gender": "Male",
"Country": [],
"State": currentImplementation.State
},
"Female": {
"Gender": "Female",
"Country": [],
"State": currentImplementation.State
}
};
for (var j=0; j<currentImplementation.Country.length; j++) {
var currentCountry = currentImplementation.Country[j];
if (currentCountry.Orientation === 'Male') {
targetObj.Male.Country.push(currentCountry);
} else if (currentCountry.Orientation === 'Female') {
targetObj.Female.Country.push(currentCountry);
}
}
finalResult.push(targetObj);
}
console.log(JSON.stringify(finalResult));
How do I add the objects like Personality Traits, Eating Habits, Reading Habits, Fitness Habits and attributes like Universal and common outside of the Implementations object in the current program?
If I am getting your question correctly, I think your code already gives you the expected JSON for Implementations property.
[
{
"Male": {
"Gender": "Male",
"Country": [
{
"Orientation": "Male",
"Name": "ABCD"
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
},
"Female": {
"Gender": "Female",
"Country": [
{
"Orientation": "Female",
"Name": "EFGH"
},
{
"Orientation": "Female",
"Name": "IJKL"
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
}
]
Therefore, if you are asking how to add the rest of the properties to achieve your expected JSON, you could just do this:
Implementations.Implementations = finalResult;
that will replace the original JSON implementations property to the one you have created.
Therefore say:
var Implementations = {
"UniversalOne": "",
"CommonOne": ""
"Implementations": [
{
"Male": {
"Gender": "Male"
},
"Female": {
"Gender": "Female"
},
"Country": [
{
"Orientation": "Male",
"Name": ABCD
},
{
"Orientation": "Female",
"Name": EFGH
},
{
"Orientation": "Female",
"Name": IJKL
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
if you do Implementations.Implementations = filteredResult;
the Implementations will become:
{
"UniversalOne": "",
"CommonOne": ""
"Implementations": [
{
"Male": {
"Gender": "Male",
"Country": [
{
"Orientation": "Male",
"Name": "ABCD"
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
},
"Female": {
"Gender": "Female",
"Country": [
{
"Orientation": "Female",
"Name": "EFGH"
},
{
"Orientation": "Female",
"Name": "IJKL"
}
],
"State": [
{
"Address": "XYZ Street",
"ZipCode": "US"
}
]
}
}
],
"PersonalityTraits": [
{
"Type": "Positive"
},
{
"Type": "Negative"
}
],
"UniversalTwo": "",
"CommonTwo": "",
"EatingHabits": {
"Type": "Excessive"
},
"ReadingHabits": {
"Type": "Fast"
},
"FitnessHabits": {
},
"UniversalThree": "",
"CommonThree": ""
}
Otherwise, explain a bit more of what you are trying to achieve.
So I have this JSON Object. Let's call it var dataFetched
var dataFetched = {
"status": "ok",
"count": 4,
"count_total": 4,
"pages": 1,
"posts": [
{
"id": 57,
"type": "keyword",
"slug": "crime-scene-investigation-csi",
"url": "http://keyjargon.com/keyword/crime-scene-investigation-csi/",
"status": "publish",
"title": "Crime Scene Investigation (CSI)",
"title_plain": "Crime Scene Investigation (CSI)",
"content": "",
"excerpt": "",
"date": "2015-11-07 05:01:51",
"modified": "2015-11-07 05:01:51",
"categories": [
{
"id": 8,
"slug": "law",
"title": "Law",
"description": "",
"parent": 0,
"post_count": 1
}
],
"tags": [
],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [
],
"attachments": [
],
"comment_count": 0,
"comment_status": "closed",
"custom_fields": {
}
},
{
"id": 50,
"type": "keyword",
"slug": "fx",
"url": "http://keyjargon.com/keyword/fx/",
"status": "publish",
"title": "FX",
"title_plain": "FX",
"content": "",
"excerpt": "",
"date": "2015-11-05 10:07:17",
"modified": "2015-11-05 10:22:10",
"categories": [
{
"id": 3,
"slug": "business",
"title": "Business",
"description": "",
"parent": 0,
"post_count": 2
}
],
"tags": [
],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [
],
"attachments": [
],
"comment_count": 0,
"comment_status": "closed",
"custom_fields": {
}
},
{
"id": 48,
"type": "keyword",
"slug": "common-core",
"url": "http://keyjargon.com/keyword/common-core/",
"status": "publish",
"title": "Common CORE",
"title_plain": "Common CORE",
"content": "",
"excerpt": "",
"date": "2015-11-05 10:06:40",
"modified": "2015-11-07 04:58:06",
"categories": [
{
"id": 2,
"slug": "technology",
"title": "Technology",
"description": "",
"parent": 0,
"post_count": 3
}
],
"tags": [
],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [
],
"attachments": [
],
"comment_count": 0,
"comment_status": "closed",
"custom_fields": {
}
},
{
"id": 46,
"type": "keyword",
"slug": "api",
"url": "http://keyjargon.com/keyword/api/",
"status": "publish",
"title": "API",
"title_plain": "API",
"content": "",
"excerpt": "",
"date": "2015-11-05 10:06:19",
"modified": "2015-11-05 10:21:47",
"categories": [
{
"id": 2,
"slug": "technology",
"title": "Technology",
"description": "",
"parent": 0,
"post_count": 3
}
],
"tags": [
],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [
],
"attachments": [
],
"comment_count": 0,
"comment_status": "closed",
"custom_fields": {
}
}
]
}
I want to rearrange this result to link the Category title :
dataFetched.posts[i].categories[0].title
to the Post title :
dataFetched.post[i].title
so that each category displays all the posts titles related to it. I want my object (whether multi-demmensional array or another object) to be able to retrieve all the Posts titles related to the category.
Maybe something like this :
[Category1: {Post_titleA, PostTitleB, PostTitleC}, Category2: {PostTileF, PostTileX}, etc ] where each category can retrieve all its posts.( The format does not matter as long the Object with Category title X can retrieve all posts titles that belong to it ).
How do I do this in Javascript ? The result variable is not static but its format is the same as the one posted here.
This is what I tried so far.
// Function to sort unique values of an array
function sort_unique(arr) {
arr = arr.sort(function (a, b) { return a*1 - b*1; });
var ret = [arr[0]];
for (var i = 1; i < arr.length; i++) { // start loop at 1 as element 0 can never be a duplicate
if (arr[i-1] !== arr[i]) {
ret.push(arr[i]);
}
}
return ret;
}
//Define two arrays to be used for categories and Keywords
var keywords = [];
var industries = [];
//Fill up the categories(Industries) array and the keywords one
for ( var i = 0, iLen = dataFetched.count; i < iLen; i++) {
keywords[i] = dataFetched.posts[i].title;
industries[i] = dataFetched.posts[i].categories[0].title;
}
// Sort and eliminate duplication of category and keyword names
keywords = sort_unique(keywords);
industries = sort_unique(industries);
// Now time for trouble: Define a multi-dimmensional array that links each category/industry to its keywords **This is where I AM STUCK**
ind = new Array;
for(i=0; i<industries.length;i++){
ind[i] = new Array;
}
for(i=0;i<dataFetched.count;i++){
ind[i][0]= dataFetched.posts[i].categories[0].title;
for(j=0;j<dataFetched.count;j++){
var count = ind[i].length;
if(ind[i][0] == dataFetched.posts[j].categories[0].title){
ind[i][count] = dataFetched.posts[j].title;
}
}
}
It is possible to create object with categories. As a result all entries can be accessed by category name and you do not need to sort them to have unique titles:
var posts = dataFetched.posts;
var cat = {};
posts.forEach(
function(p) {
p.categories.forEach(
function(c) {
if (!cat[c.title])
cat[c.title] = [];
cat[c.title].push(p.title);
});
});
console.log(cat);
Output for your example:
Object {Law: Array[1], Business: Array[1], Technology: Array[2]}
Each category title is a key in this object and the arrays of posts are values of those keys.
The output example you showed is wrong, in JS there's no object like
[Category1: {Post_titleA, PostTitleB, PostTitleC}, Category2: {PostTileF, PostTileX}, etc ]
The most similar thing you can get is a JSON object like this:
{
"Category1" : ["Post_titleA", "PostTitleB", "PostTitleC"],
"Category2" : ["PostTileF", "PostTileX"],
//etc..
}
In order to achieve this, you can use the following function:
function getTitlesByCategory (json) {
var result = {}
json.posts.map(function (post) {
post.categories.map(function (category) {
result[category.title] = result[category.title] || [];
result[category.title].push(post.title);
});
});
return result;
}