I am new to node.js and javascript. I am trying to build a rest API.
For a specific purpose, I need to convert an object to 3d array.
I tried running for, foreach loop but it is not providing what I am trying to achieve.
My object looks like this.
"data": [
{
"id": 15184,
"badge_id": "330886",
"name": "Rukmani J. Solanki",
"gender": "Female",
"type": "PF",
"department": "Sales",
"checkin": "2021-09-24T08:52:44.000Z",
"checkout": "2021-09-24T08:57:45.000Z",
"hours": "00:05"
},
{
"id": 15185,
"badge_id": "440886",
"name": "Jairam J. Solanki",
"gender": "Male",
"type": "PM",
"department": "Sales",
"checkin": "2021-09-24T09:28:32.000Z",
"checkout": null,
"hours": null
}
]
And I want something like this
{
"onfield": [
{
"key": "Sales",
"data": {
"PM": [
{
"name": "Gokuldas S. Sundrani",
"badge_id": "441101",
"gender": "Male",
"checkIn": "2021-09-24 06:04:18",
"checkOut": null,
"hours": "NoCheckOut"
},
{
"name": "Satnamsingh M. Chhabra",
"badge_id": "551249",
"gender": "Male",
"checkIn": "2021-09-24 06:47:31",
"checkOut": "2021-09-24 08:32:00",
"hours": "1.7 Hours"
},
{
"name": "Praveen N. Jethwani",
"badge_id": "771328",
"gender": "Male",
"checkIn": "2021-09-24 07:14:11",
"checkOut": "2021-09-24 08:29:34",
"hours": "1.3 Hours"
},
{
"name": "Satnamsingh M. Chhabra",
"badge_id": "88249",
"gender": "Male",
"checkIn": "2021-09-24 08:32:00",
"checkOut": null,
"hours": "NoCheckOut"
},
{
"name": "Arjundas D. Chhabra",
"badge_id": "661248",
"gender": "Male",
"checkIn": "2021-09-24 10:19:22",
"checkOut": "2021-09-24 18:38:32",
"hours": "8.3 Hours"
},
{
"name": "Parmanand C. Lalwani",
"badge_id": "8651418",
"gender": "Male",
"checkIn": "2021-09-24 14:51:08",
"checkOut": "2021-09-24 17:39:27",
"hours": "2.8 Hours"
},
{
"name": "Dhanalal G. Chouhan",
"badge_id": "5501392",
"gender": "Male",
"checkIn": "2021-09-24 14:58:46",
"checkOut": "2021-09-24 18:20:50",
"hours": "3.4 Hours"
}
],
"PF": [
{
"name": "Baljeetkaur S. Chhabra",
"badge_id": "501993",
"gender": "Female",
"checkIn": "2021-09-24 06:47:48",
"checkOut": "2021-09-24 08:32:12",
"hours": "1.7 Hours"
},
{
"name": "Baljeetkaur S. Chhabra",
"badge_id": "801993",
"gender": "Female",
"checkIn": "2021-09-24 08:32:12",
"checkOut": null,
"hours": "NoCheckOut"
}
],
"OM": [
{
"name": "Yadvendra Bhati",
"badge_id": "2255454",
"gender": "male",
"checkIn": "2021-09-24 13:38:37",
"checkOut": "2021-09-24 17:24:11",
"hours": "3.8 Hours"
}
],
"OF": [
{
"name": "Yashoda Bhati",
"badge_id": "223F0029",
"gender": "Female",
"checkIn": "2021-09-24 13:38:44",
"checkOut": "2021-09-24 17:24:25",
"hours": "3.8 Hours"
}
]
}
}
]
}
How can this be done?
I will be really grateful to you for your help.
I have googled and searched StackOverflow but did not find anything which deals with this kind of problem.
Thank You
Although I totally agree with Juan Mendes, here is a tip in order for you to be able to accomplish this. You may get an intermediate form for your data as this one:
{
"onfield": [
{
"key": "dept1",
"data": {
"PM": [
{
"id": 123,
"badge_id": "1231",
"name": "name1",
"gender": "Male"
}
]
}
},
{
"key": "dept2",
"data": {
"PF": [
{
"id": 124,
"badge_id": "1232",
"name": "name2",
"gender": "Female"
}
]
}
},
{
"key": "dept1",
"data": {
"PM": [
{
"id": 125,
"badge_id": "1233",
"name": "name3",
"gender": "Male",
"type": "PM",
"dept": "dept1"
}
]
}
}
]
}
Perhaps transforming your source data to this one is easier. And getting to your target from here will be just a matter of merging arrays of the same type.
Do not hesitate to ask if this keeps being difficult. But as said, please try to solve this yourself, that's the way you are going to learn.
let data = [{ "id": 123, "badge_id": "1231", "name": "name1", "gender": "Male", "type": "PM", "dept": "dept1" }, { "id": 124, "badge_id": "1232", "name": "name2", "gender": "Female", "type": "PF", "dept": "dept2" }, { "id": 125, "badge_id": "1233", "name": "name3", "gender": "Male", "type": "PM", "dept": "dept1" }];
let Report = []
data.forEach((item) => {
let obj = Report.find(v => v.dept == item.dept);
if (!obj) Report.push(obj = {
dept: item.dept,
type: {}
});
obj.type[item.type] ??= [];
obj.type[item.type].push({
id: item.id,
badge_id: item.badge_id,
name: item.name,
gender: item.gender,
});
})
console.log(Report)
Here's Something i think is more feasible than your result .. Checkout
let myObject = {
"data": [ {
"id": 123,
"badge_id": "1231",
"name": "name1",
"gender": "Male",
"type": "PM",
"dept": "dept1"
},
{
"id": 124,
"badge_id": "1232",
"name": "name2",
"gender": "Female",
"type": "PF",
"dept": "dept2"
},
{
"id": 125,
"badge_id": "1233",
"name": "name3",
"gender": "Male",
"type": "PM",
"dept": "dept1"
}]
}
function generateReport(object) {
let obj = {
"Report": []
};
let types = [];
object.data.forEach(arr =>{
if(!types.includes(arr.type)){
types.push(arr.type);
}
});
types.forEach(type =>{
obj.Report.push({
type : type,
users : object.data.filter(arr=>{ let a = arr.type == type;
if(a){
delete arr.type;
}
return a;
})
});
});
return obj;
}
myObject = generateReport(myObject);
console.log(myObject)
You oculd take the wanted grouping keys in an array and destructure the object to remove this keys from the object.
Every key takes it own nested object structure.
const
data = [{ id: 123, badge_id: "1231", name: "name1", gender: "Male", type: "PM", dept: "dept1" }, { id: 124, badge_id: "1232", name: "name2", gender: "Female", type: "PF", dept: "dept2" }, { id: 125, badge_id: "1233", name: "name3", gender: "Male", type: "PM", dept: "dept1" }],
keys = ['dept', 'type'],
result = data
.reduce((r, o) => {
keys
.reduce(function (t, k) {
let key;
({ [k]: key, ...o } = o);
if (!t[key]) t._.push({ [k]: key, data: (t[key] = { _: [] })._ });
return t[key];
}, r)
._
.push(o);
return r;
}, { _: [] })
._;
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related
I have an array of employees. when i map trough this array and retrieve values of objects using dot notation everything works fine for top level objects but sub objects return value for employee.jobtitle.jobdesc of only first object.
All remaining objects records for employee.jobtitle.jobdesc are empty. Below is array. i am using map.employees method to iterate through array and rendering output using ( {employee.id} {employee.firstname} {employee.lastname} and {employee.jobtitle.jobdesc}. Why nested objects are only returning output for only first object e.g. Edward whereas for other Salesman it is not returning anything.
[
{
"id": 1,
"firstname": "John",
"lastname": "Bob",
"gender": "Male",
"nationalId": 1212121212,
"jobtitle": {
"id": 1,
"jobdesc": "General Manager"
}
},
{
"id": 2,
"firstname": "Edward",
"lastname": "Rick",
"gender": "Male",
"nationalId": 1212121212,
"jobtitle": {
"id": 2,
"jobdesc": "Salesman"
}
},
{
"id": 3,
"firstname": "Mike",
"lastname": "Arther",
"gender": "Male",
"nationalId": 1212121212,
"jobtitle": {
"id": 3,
"jobdesc": "Sales"
}
},
{
"id": 4,
"firstname": "Nick",
"lastname": "Johns",
"gender": "Male",
"nationalId": 1212121212,
"jobtitle": {
"id": 4,
"jobdesc": "Salesman"
}
}
]
Here is a solution that uses Array map(). You can read more about it in the link below.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
const employees = [
{
"id": 1,
"firstname": "John",
"lastname": "Bob",
"gender": "Male",
"nationalId": 1212121212,
"jobtitle": {
"id": 1,
"jobdesc": "General Manager"
}
},
{
"id": 2,
"firstname": "Edward",
"lastname": "Rick",
"gender": "Male",
"nationalId": 1212121212,
"jobtitle": {
"id": 2,
"jobdesc": "Salesman"
}
},
{
"id": 3,
"firstname": "Mike",
"lastname": "Arther",
"gender": "Male",
"nationalId": 1212121212,
"jobtitle": {
"id": 3,
"jobdesc": "Sales"
}
},
{
"id": 4,
"firstname": "Nick",
"lastname": "Johns",
"gender": "Male",
"nationalId": 1212121212,
"jobtitle": {
"id": 4,
"jobdesc": "Salesman"
}
}
];
const allJobs = employees
.map(employee => employee.jobtitle.jobdesc);
console.log(allJobs);
React example
const employees = [{
"id": 1,
"firstname": "John",
"lastname": "Bob",
"gender": "Male",
"nationalId": 1212121212,
"jobtitle": {
"id": 1,
"jobdesc": "General Manager"
}
},
{
"id": 2,
"firstname": "Edward",
"lastname": "Rick",
"gender": "Male",
"nationalId": 1212121212,
"jobtitle": {
"id": 2,
"jobdesc": "Salesman"
}
},
{
"id": 3,
"firstname": "Mike",
"lastname": "Arther",
"gender": "Male",
"nationalId": 1212121212,
"jobtitle": {
"id": 3,
"jobdesc": "Sales"
}
},
{
"id": 4,
"firstname": "Nick",
"lastname": "Johns",
"gender": "Male",
"nationalId": 1212121212,
"jobtitle": {
"id": 4,
"jobdesc": "Salesman"
}
}
];
const PersonList = () => {
return employees.map(employee => (
<div key={employee.id}>
<h2>{employee.firstname} {employee.lastname}</h2>
<h3>{employee.jobtitle.jobdesc}</h3>
<hr />
</div>
))
}
ReactDOM.render(<PersonList />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app">
</div>
Vanilla JavaScript example
const employees = [{
"id": 1,
"firstname": "John",
"lastname": "Bob",
"gender": "Male",
"nationalId": 1212121212,
"jobtitle": {
"id": 1,
"jobdesc": "General Manager"
}
},
{
"id": 2,
"firstname": "Edward",
"lastname": "Rick",
"gender": "Male",
"nationalId": 1212121212,
"jobtitle": {
"id": 2,
"jobdesc": "Salesman"
}
},
{
"id": 3,
"firstname": "Mike",
"lastname": "Arther",
"gender": "Male",
"nationalId": 1212121212,
"jobtitle": {
"id": 3,
"jobdesc": "Sales"
}
},
{
"id": 4,
"firstname": "Nick",
"lastname": "Johns",
"gender": "Male",
"nationalId": 1212121212,
"jobtitle": {
"id": 4,
"jobdesc": "Salesman"
}
}
];
const appDiv = document.getElementById('app');
employees.forEach(employee => {
const empDiv = document.createElement('div');
empDiv.setAttribute('id', employee.id);
const empH2 = document.createElement('h2');
empH2.innerText = `${employee.firstname} ${employee.lastname}`;
empDiv.append(empH2);
const empH3 = document.createElement('h3');
empH3.innerText = employee.jobtitle.jobdesc;
empDiv.append(empH3);
const divider = document.createElement('hr');
empDiv.append(divider);
appDiv.append(empDiv);
});
<div id="app">
</div>
I have a nested (up to 21 deep) JSON in the following format:
{
"name": "Unknown Wife",
"id": 341,
"house": "Tyrell",
"gender": "Female",
"partnerId": 340,
"hasParnter": true,
"noParent": true,
"children": [{
"name": "Olymer",
"id": 342,
"house": "Tyrell",
"gender": "Male",
"partnerId": 343,
"hasParnter": true,
"isSource": true
}, {
"name": "Lysa Meadows",
"id": 343,
"house": "Tyrell",
"gender": "Female",
"partnerId": 342,
"hasParnter": true,
"noParent": true,
"children": [{
"name": "Raymund",
"id": 344,
"house": "Tyrell",
"gender": "Male",
"isSource": true
}, {
"name": "Rickard",
"id": 345,
"house": "Tyrell",
"gender": "Male",
"isSource": true
}, {
"name": "Megga",
"id": 346,
"house": "Tyrell",
"gender": "Female",
"isSource": true
}]
I am trying to transform this data into the format
{name: "someName", children:["all","children","deeper","in","object"]},
So presumably, highest level members of the original object would have the longest array of children. Within a single lineage, this would reduce as you worked deeper down the family tree.
What is the best route for recursively working into the family tree and returning to a new object in the format directly above?
You should use Reduce recursively.
var person = {"name":"Unknown Wife","id":341,"house":"Tyrell","gender":"Female","partnerId":340,"hasParnter":true,"noParent":true,"children":[{"name":"Olymer","id":342,"house":"Tyrell","gender":"Male","partnerId":343,"hasParnter":true,"isSource":true},{"name":"Lysa Meadows","id":343,"house":"Tyrell","gender":"Female","partnerId":342,"hasParnter":true,"noParent":true,"children":[{"name":"Raymund","id":344,"house":"Tyrell","gender":"Male","isSource":true},{"name":"Rickard","id":345,"house":"Tyrell","gender":"Male","isSource":true},{"name":"Megga","id":346,"house":"Tyrell","gender":"Female","isSource":true}]}]};
function printAll(p1) {
print(p1);
if (p1.children) {
p1.children.forEach(c => printAll(c))
}
}
function print(p1) {
console.log({person: p1.name, descendents: (p1.children || []).reduce(GetChildren, [])});
}
function GetChildren(children, child) {
return children.concat(child.name).concat((child.children || []).reduce(GetChildren, []));
}
<button onclick="print(person)">Print main person</button>
<button onclick="printAll(person)">Print for all</button>
It's not very clear to me from your question what's the desired result exactly but it's definitely recursion what you are after, I will assume you want something like this
obj={ "name": "Unknown Wife", "id": 341, "house": "Tyrell", "gender": "Female", "partnerId": 340, "hasParnter": true, "noParent": true, "children": [{ "name": "Olymer", "id": 342, "house": "Tyrell", "gender": "Male", "partnerId": 343, "hasParnter": true, "isSource": true }, { "name": "Lysa Meadows", "id": 343, "house": "Tyrell", "gender": "Female", "partnerId": 342, "hasParnter": true, "noParent": true, "children": [{ "name": "Raymund", "id": 344, "house": "Tyrell", "gender": "Male", "isSource": true }, { "name": "Rickard", "id": 345, "house": "Tyrell", "gender": "Male", "isSource": true }, { "name": "Megga", "id": 346, "house": "Tyrell", "gender": "Female", "isSource": true }] }] }
results=[]
children=[]
function myfunc(myObj){
if(myObj.name){
myObj.children.forEach(o=>{
if(!o.children){
children.push(o)
results.push({name:myObj.name,children:children})
}
else {
children.push({name:o.name,id:o.id,house:o.house,gender:o.gender,partnerId:o.partnerId,hasParnter:o.hasParnter,noParent:o.noParent})}
})
}
if(Array.isArray(myObj.children)){
for(let i=0; i<myObj.children.length; i++){
if(!myObj.children[i].children) continue
if(myObj.children[i].name) results.push({name:myObj.children[i].name,children:[myObj.children[i].children]})
else myfunc(myObj.children[i])
}
}
}
myfunc(obj)
console.log(results)
I have JSON like below, I need to filter out workers having the age less than 25.
var employee = {
"value": [
{
"position": "Seniro Developer",
"description": "Developemwnt",
"workers": [
{
"name": "Kumar",
"age": 22
},
{
"name": "aravinth",
"age": 29
},
{
"name": "sathish",
"age": 35
}
]
},
{
"position": "Tester",
"description": "testing",
"workers": [
{
"name": "vinth",
"age": 18
},
{
"name": "rahul",
"age": 45
},
{
"name": "sathish",
"age": 12
}
]
}
]
}
I have tried to use the below code, but it returns all the value inside the workers array, but my expectation is it should return only the employee having than 25.
If I use Map function it is affecting the employee Object also.
var filteredResult = employee.filter(e => e.workers.some(w => w.age < 25))
Expected Result:
{
"value": [
{
"position": "Seniro Developer",
"description": "Developemwnt",
"workers": [
{
"name": "Kumar",
"age": 22
}
]
},
{
"position": "Tester",
"description": "testing",
"workers": [
{
"name": "vinth",
"age": 18
},
{
"name": "sathish",
"age": 12
}
]
}
]
}
You can do it with a map and a filter, to avoid to modify the original array, you can use Object.asign
var employee = {
"value": [{
"position": "Seniro Developer",
"description": "Developemwnt",
"workers": [{
"name": "Kumar",
"age": 22
},
{
"name": "aravinth",
"age": 29
},
{
"name": "sathish",
"age": 35
}
]
},
{
"position": "Tester",
"description": "testing",
"workers": [{
"name": "vinth",
"age": 18
},
{
"name": "rahul",
"age": 45
},
{
"name": "sathish",
"age": 12
}
]
}
]
}
var filteredResult = employee.value.map(e => {
let filter = e.workers.filter(w => w.age < 25)
return Object.assign({}, e, {workers: filter})
})
console.log('original', employee)
console.log('result', filteredResult)
You could reduce the array and check if the filtered workers have some elements then push a new object with changed workers to the result set.
var employee = { value: [{ position: "Seniro Developer", description: "Developemwnt", workers: [{ name: "Kumar", age: 22 }, { name: "aravinth", age: 29 }, { name: "sathish", age: 35 }] }, { position: "Tester", description: "testing", workers: [{ name: "vinth", age: 18 }, { name: "rahul", age: 45 }, { name: "sathish", age: 12 }] }] },
value = employee.value.reduce((r, o) => {
const workers = o.workers.filter(({ age }) => age < 25);
if (workers.length) r.push({ ...o, workers });
return r;
}, []),
result = { value };
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can also try this:
var employee = { "value": [ { "position": "Seniro Developer", "description": "Developemwnt", "workers": [ { "name": "Kumar", "age": 22 }, { "name": "aravinth", "age": 29 }, { "name": "sathish", "age": 35 } ] }, { "position": "Tester", "description": "testing", "workers": [ { "name": "vinth", "age": 18 }, { "name": "rahul", "age": 45 }, { "name": "sathish", "age": 12 } ] } ]}
result = employee.value.map(({workers, ...rest})=>({...rest, workers:[...workers.filter(k=>k.age<25)]}));
console.log(result);
Use map and while creating the workers key in return object use filter to get employee with age less than 25. map will create an array
var employee = {
"value": [{
"position": "Seniro Developer",
"description": "Developemwnt",
"workers": [{
"name": "Kumar",
"age": 22
},
{
"name": "aravinth",
"age": 29
},
{
"name": "sathish",
"age": 35
}
]
},
{
"position": "Tester",
"description": "testing",
"workers": [{
"name": "vinth",
"age": 18
},
{
"name": "rahul",
"age": 45
},
{
"name": "sathish",
"age": 12
}
]
}
]
}
let filteredEmployee = employee.value.map((item) => {
return {
"position": item.position,
"description": item.description,
"workers": item.workers.filter(elem => elem.age < 25)
}
});
let newObject = Object.assign({}, {
value: filteredEmployee
});
console.log(newObject)
You can use map method with ... rest syntax:
employee.value.map(({workers, ...rest}) => ({...rest,
workers: workers.filter(w => w.age < 25)}));
An example:
let employee = {
"value": [
{
"position": "Seniro Developer",
"description": "Developemwnt",
"workers": [
{
"name": "Kumar",
"age": 22
},
{
"name": "aravinth",
"age": 29
},
{
"name": "sathish",
"age": 35
}
]
},
{
"position": "Tester",
"description": "testing",
"workers": [
{
"name": "vinth",
"age": 18
},
{
"name": "rahul",
"age": 45
},
{
"name": "sathish",
"age": 12
}
]
}
]
}
const result = employee.value.map(({workers, ...rest}) => ({...rest, workers: workers.filter(w => w.age < 25)}));
console.log(result);
I've got the following object and I'm trying to filter and return players from both groups based on multiple criteria such as "show me all players where franchise = Marvel, and power= flight" but I'm getting hung up in multiple levels of filtering.
I was looking at this answer but it doesn't seem to fit my scenario: JavaScript - Filter object based on multiple values
I can get results if I iterate over the groups but there are potentially lots of groups and I didn't want to get hung up in that. Is that the best way, though?
oPlayers.players.groups.filter(function(hero){return hero.Id == 1})
oPlayers = {
"players": {
"groups": [
{
"Id": 1,
"hero": [
{
"Id": 1,
"name": "Batman",
"franchise": "DC",
"gender": "Male",
"powers": [{"power":"stealth"},{"power":"intelligence"},{"power":"weaponry"}]
},
{
"Id": 2,
"name": "Ironman",
"franchise": "Marvel",
"gender": "Male",
"powers": [{"power":"flight"},{"power":"intelligence"},{"power":"weaponry"}]
},
{
"Id": 3,
"name": "Supergirl",
"franchise": "DC",
"gender": "Female",
"powers": [{"power":"flight"},{"power":"strength"},{"power":"speed"}]
},
{
"Id": 4,
"name": "Valkyrie",
"franchise": "Marvel",
"gender": "Female",
"powers": [{"power":"flight"},{"power":"intelligence"},{"power":"strength"}]
}
]
},
{
"Id": 2,
"hero": [
{
"Id": 1,
"name": "Batwoman",
"franchise": "DC",
"gender": "Female",
"powers": [{"power":"stealth"},{"power":"intelligence"},{"power":"weaponry"}]
},
{
"Id": 2,
"name": "IronPepper",
"franchise": "Marvel",
"gender": "Female",
"powers": [{"power":"flight"},{"power":"intelligence"},{"power":"weaponry"}]
},
{
"Id": 3,
"name": "Superman",
"franchise": "DC",
"gender": "Male",
"powers": [{"power":"flight"},{"power":"strength"},{"power":"speed"}]
},
{
"Id": 4,
"name": "Thor",
"franchise": "Marvel",
"gender": "Male",
"powers": [{"power":"flight"},{"power":"intelligence"},{"power":"strength"}]
}
]
}
]
}
}
You can first use flatMap to get a single list of all players. Then, given that your criteria is specified as an object, you can filter players based on whether every property specified in criteria matches properties of a player:
function filter(players, criteria) {
return players.players.groups.flatMap(({Id, hero}) =>
hero.filter(p =>
Object.entries(criteria).every(([k, v]) => {
if (k === 'power') return p.powers.some(({power}) => power === v);
return p[k] === v;
}))
.map(p => ({groupId: Id, ...p})));
}
const oPlayers = {
"players": {
"groups": [{
"Id": 1,
"hero": [{
"Id": 1,
"name": "Batman",
"franchise": "DC",
"gender": "Male",
"powers": [{
"power": "stealth"
}, {
"power": "intelligence"
}, {
"power": "weaponry"
}]
},
{
"Id": 2,
"name": "Ironman",
"franchise": "Marvel",
"gender": "Male",
"powers": [{
"power": "flight"
}, {
"power": "intelligence"
}, {
"power": "weaponry"
}]
},
{
"Id": 3,
"name": "Supergirl",
"franchise": "DC",
"gender": "Female",
"powers": [{
"power": "flight"
}, {
"power": "strength"
}, {
"power": "speed"
}]
},
{
"Id": 4,
"name": "Valkyrie",
"franchise": "Marvel",
"gender": "Female",
"powers": [{
"power": "flight"
}, {
"power": "intelligence"
}, {
"power": "strength"
}]
}
]
},
{
"Id": 2,
"hero": [{
"Id": 1,
"name": "Batwoman",
"franchise": "DC",
"gender": "Female",
"powers": [{
"power": "stealth"
}, {
"power": "intelligence"
}, {
"power": "weaponry"
}]
},
{
"Id": 2,
"name": "IronPepper",
"franchise": "Marvel",
"gender": "Female",
"powers": [{
"power": "flight"
}, {
"power": "intelligence"
}, {
"power": "weaponry"
}]
},
{
"Id": 3,
"name": "Superman",
"franchise": "DC",
"gender": "Male",
"powers": [{
"power": "flight"
}, {
"power": "strength"
}, {
"power": "speed"
}]
},
{
"Id": 4,
"name": "Thor",
"franchise": "Marvel",
"gender": "Male",
"powers": [{
"power": "flight"
}, {
"power": "intelligence"
}, {
"power": "strength"
}]
}
]
}
]
}
};
console.log(filter(oPlayers, {gender: 'Male', franchise: 'Marvel'}));
console.log(filter(oPlayers, {gender: 'Female', power: 'flight'}));
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.