Reformat json data using Jquery - javascript

I need to convert the following JSON data:
var response = {
"data": {
"List": [
{
"Name": "Mary",
"state": "AZ",
"Matriculation": "complete",
"Graduation": "complete",
"Masters": "complete",
"Phd": "notStarted"
},
{
"Name": "Stephanie",
"state": "CT",
"Matriculation": "complete",
"Graduation": "complete",
"Masters": "complete",
"Phd": "notStarted"
},
{
"Name": "John",
"state": "CT",
"Matriculation": "complete",
"Graduation": "planning",
"Masters": "notStarted",
"Phd": "notStarted"
}]
}
}
into the following using jQuery:
[
{
"state":"AZ",
"Matriculation":[
{
"Name":"Mary",
"status":"complete"
}
],
"Graduation":[
{
"Name":"Mary",
"status":"complete"
}
],
"Masters":[
{
"Name":"Mary",
"status":"complete"
}
],
"Phd":[
{
"Name":"Mary",
"status":"notStarted"
}
]
},
{
"state":"CT",
"Matriculation":[
{
"Name":"Stephanie",
"status":"complete"
},
{
"Name":"John",
"status":"complete"
}
],
"Graduation":[
{
"Name":"Stephanie",
"status":"complete"
},
{
"Name":"John",
"status":"planning"
}
],
"Masters":[
{
"Name":"Stephanie",
"status":"complete"
},
{
"Name":"John",
"status":"notStarted"
}
],
"Phd":[
{
"Name":"Stephanie",
"status":"notStarted"
},
{
"Name":"John",
"status":"notStarted"
}
]
}
]
This is what I have tried so far with zero progress.
I tried to accomplish this for one state first.
This is the fiddle:
http://jsfiddle.net/sqgdyk6f/
Any guidance is appreciated.
I am new to JSON manipulation.
Thanks in advance!

First thing you should do is analyze your source format, and your destination format.
Your source format is just an array of objects of individual people.
Your destination format is an object that groups the people by state
and into certain categories.
Next, think about how you can get the source into this destination.
You're going to want to iterate over each individual person in the source, and try to add it to your array of states. Now, I'll say your destination format is a bit peculiar, but by writing a couple of helper functions, you can achieve that format.
Take a look at your destination format again. It's an array of objects. Part of each object in that array is a property called state that has a value for the state that object represents. You're going to want a function that can look through this array for a specific state, and return the existing object for you. If the state doesn't exist, it should add a new entry to the array for you and return that.
Since JSON just means JavaScript Object Notation, and you are actually working with JavaScript objects, you should create an object that models each entry of your destination array. I'm going to call these StateSummary.
function StateSummary(state) {
this.state = state;
this.Matriculation = [];
this.Graduation = [];
this.Masters = [];
this.Phd = [];
}
Can you see how this object represents each entry in your destination array?
Now that you have an object that models each entry, we need a function that can check to see if an entry for a certain state already exists. If it exists, it will return that object. If it doesn't exist, it will add a new object to the array, and return this new object.
function addOrGetState(array, state) {
for (var i = 0; i < array.length; i++) {
var obj = array[i];
if (obj.state === state)
return obj;
}
//If the function got here, then it didn't find a matching state.
var obj = new StateSummary(state);
array.push(obj); //Add the new object to the array.
return obj; //Return the new object.
}
So, now you can get an entry by state from your destination array, and you can create new entries.
Go ahead and create a function that will add a person to a StateSummary object.
function addPersonToStateSummary(person, stateSummary) {
stateSummary.Matriculation.push({ Name: person.Name, status: person.Matriculation });
stateSummary.Graduation.push({ Name: person.Name, status: person.Graduation});
stateSummary.Masters.push({ Name: person.Name, status: person.Masters});
stateSummary.Phd.push({ Name: person.Name, status: person.Phd});
}
The last piece is iterating over the source array, and massaging that data into your destination array.
var sourceArray = response.data.List; //You provided this.
var destinationArray = []; //Allocate a new array to put stuff in.
for (var i = 0; i < sourceArray.length; i++) {
var person = sourceArray[i]; //Each entry of the source array represents a person.
var stateSummary = addOrGetState(destinationArray, person.state);
addPersonToStateSummary(person, stateSummary);
}
This should give you what you are looking for. I hope this breakdown teaches you how to think about the problem in an analytical way, breaking its steps down first, and then solving them with code.
Here is a demo:
var response = {
"data": {
"List": [{
"Name": "Mary",
"state": "AZ",
"Matriculation": "complete",
"Graduation": "complete",
"Masters": "complete",
"Phd": "notStarted"
}, {
"Name": "Stephanie",
"state": "CT",
"Matriculation": "complete",
"Graduation": "complete",
"Masters": "complete",
"Phd": "notStarted"
}, {
"Name": "John",
"state": "CT",
"Matriculation": "complete",
"Graduation": "planning",
"Masters": "notStarted",
"Phd": "notStarted"
}]
}
};
function StateSummary(state) {
this.state = state;
this.Matriculation = [];
this.Graduation = [];
this.Masters = [];
this.Phd = [];
}
function addOrGetState(array, state) {
for (var i = 0; i < array.length; i++) {
var obj = array[i];
if (obj.state === state)
return obj;
}
//If the function got here, then it didn't find a matching state.
var obj = new StateSummary(state);
array.push(obj); //Add the new object to the array.
return obj; //Return the new object.
}
function addPersonToStateSummary(person, stateSummary) {
stateSummary.Matriculation.push({
Name: person.Name,
status: person.Matriculation
});
stateSummary.Graduation.push({
Name: person.Name,
status: person.Graduation
});
stateSummary.Masters.push({
Name: person.Name,
status: person.Masters
});
stateSummary.Phd.push({
Name: person.Name,
status: person.Phd
});
}
var sourceArray = response.data.List; //You provided this.
var destinationArray = []; //Allocate a new array to put stuff in.
for (var i = 0; i < sourceArray.length; i++) {
var person = sourceArray[i]; //Each entry of the source array represents a person.
var stateSummary = addOrGetState(destinationArray, person.state);
addPersonToStateSummary(person, stateSummary);
}
document.getElementById('result').innerHTML = JSON.stringify(destinationArray);
<div id="result"></div>

Related

Problems extracting property names from an object (JAVASCRIPT)

I have an array of objects (I think!) and I need to extract the property name (for example "nickname") from a given object.
With
var VarObjAndValue = newArr[0];
I get the individual arrays (for example Object { nickname: “jhonny” }).
How can I now extract the property name "nickname" from the object above?
Listing the keys with
var listPropertyNames = Object.keys(newArr);
only provides sequential numbers from 0 to 6 rather than the desired keys names..
var StrToInclude = ["nickname", "name", "surname", "sex", "dob", "email", "phone"];
var newArr=[]; //Key name + its value
for (var i=0; i<StrToInclude.length; i++) {
temp_obj = {};
temp_obj[StrToInclude[i]] = document.getElementById(StrToInclude[i]).value;
newArr.push(temp_obj);
}
console.log('newArr --> = ',newArr);
/**
* newArr = [
* { "nickname": “jhonny” },
* { "name": “jonathan” },
* { "surname": “ross” },
* { "sex": “male” },
* { "dob": “22/02/1984” },
* { "email": “j#yahoo.com” },
* { "phone": "123" }
* ]
*/
var VarObjAndValue = newArr[0];
console.log('VarObjAndValue --> = ',VarObjAndValue); //if i=0 ----> Object { nickname: “jhonny” }
var VarObjAndValue = newArr[1];
console.log('VarObjAndValue --> = ',VarObjAndValue); //if i=1 ----> Object { name: "jonathan" }
var listPropertyNames = Object.keys(newArr);
console.log('listPropertyNames --> = ',listPropertyNames); //Array(7) [ "0", "1", "2", "3", "4", "5", "6" ] (not useful for this...)
newArr.map(obj => Object.keys(obj)).flat()
or newArr.map(obj => Object.keys(obj)[0])
or from dave's comment
newArr.reduce((keys, o) => [...keys, ...Object.keys(o)], [])
gives you all property names as an array
Not sure if this is what you want, but you have already gotten those property names in StrToInclude
const newArr =
[
{
"nickname": "jhonny"
},
{
"name": "jonathan"
},
{
"surname": "ross"
},
{
"sex": "male"
},
{
"dob": "22/02/1984"
},
{
"email": "j#yahoo.com"
},
{
"phone": "123"
}
]
console.log(newArr.map(obj => Object.keys(obj)[0]))
You are very close to getting the right answer. Since newArr is an Array, the keys are numeric keys. All you have to do is go through each element is the Array of Objects to extract the keys. Something like this should do nicely:
for(let i = 0;i<newArr.length;i++){
console.log(Object.keys(newArr[i])); //Will go through the whole array and give you the keys of every object in it
}
You can simply do by looping over the array and using destructuring operator with the desired property name.
const arr = [
{
nickname: "abdullah"
},
{
age: 27
}
];
arr.forEach(({nickname}) => {
if (nickname) {
console.log(`Thats the property we want to extract: ${nickname}`);
break; // if you are not expecting this property name in other objects, otherwise no need to break
}
});

How to append object-key value form one array to other array?

I have an existing array with multiple object. With an interval I would like to update the existing array with values from another array. See the (simplified) example below.
I've serverall gools:
Copy the value of fan_count form the new array, to the current array with the key "fan_count_new"
If a object is removed or added in the New array, it have to do the same to the Current array.
As far I can see now, I can use some es6 functions :) like:
object-assign, but how to set the new key "fan_count_new"?
How to loop through the array to compare and add or remove + copy the fan_count?
Current array:
[{
"fan_count": 1234,
"id": "1234567890",
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
}
},
{
"fan_count": 4321,
"id": "09876543210",
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
}
}, ...
]
New array:
[{
"fan_count": 1239,
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
"id": "1234567890"
},
{
"fan_count": 4329,
"picture": {
"data": {
"url": "https://scontent.xx.fbcdn.net/v/photo.png"
}
},
"id": "09876543210"
}, ...
]]
You can remove elements which doesn't exists in new array by using array.filter and you can loop through the new array to update the same object in the current array:
var currArr = [
{
"fan_count": 1234,
"id": "1234567890",
},
{
"fan_count": 4321,
"id": "09876543210",
},
{
"fan_count": 4321,
"id": "09876543215",
}
];
var newArr = [
{
"fan_count": 1234,
"id": "1234567890"
},
{
"fan_count": 5555,
"id": "09876543210"
}
];
currArr = currArr.filter(obj => newArr.some(el => el.id === obj.id));
newArr.forEach(obj => {
var found = currArr.find(o => o.id === obj.id);
if (found) {
found.fan_count_new = obj.fan_count;
}
});
console.log(currArr);
Later on I realised that is was better to turn it around, add the fan_count form the currArr to the new one. This because it is easier to handle new objects, and you dont't have to deal with deleted objects. So, anybody how is looking for something like this:
newArr.forEach(obj => {
var found = currArr.find(o => o.id === obj.id);
if (found) {
console.log('found: ', found.fan_count, obj.fan_count)
obj.fan_count_prev = found.fan_count;
obj.fan_count_diff = Math.round(obj.fan_count - found.fan_count);
}
if (typeof obj.fan_count_prev === "undefined") {
obj.fan_count_prev = obj.fan_count;
obj.fan_count_diff = 0
}
});

Rename json keys iterative

I got a very simple json but in each block I got something like this.
var json = {
"name": "blabla"
"Children": [{
"name": "something"
"Children": [{ ..... }]
}
And so on. I don't know how many children there are inside each children recursively.
var keys = Object.keys(json);
for (var j = 0; j < keys.length; j++) {
var key = keys[j];
var value = json[key];
delete json[key];
key = key.replace("Children", "children");
json[key] = value;
}
And now I want to replace all "Children" keys with lowercase "children". The following code only works for the first depth. How can I do this recursively?
It looks the input structure is pretty well-defined, so you could simply create a recursive function like this:
function transform(node) {
return {
name: node.name,
children: node.Children.map(transform)
};
}
var json = {
"name": "a",
"Children": [{
"name": "b",
"Children": [{
"name": "c",
"Children": []
}, {
"name": "d",
"Children": []
}]
}, {
"name": "e",
"Children": []
}]
};
console.log(transform(json));
A possible solution:
var s = JSON.stringify(json);
var t = s.replace(/"Children"/g, '"children"');
var newJson = JSON.parse(t);
Pros: This solution is very simple, being just three lines.
Cons: There is a potential unwanted side-effect, consider:
var json = {
"name": "blabla",
"Children": [{
"name": "something",
"Children": [{ ..... }]
}],
"favouriteWords": ["Children","Pets","Cakes"]
}
The solution replaces all instances of "Children", so the entry in the favouriteWords array would also be replaced, despite not being a property name. If there is no chance of the word appearing anywhere else other than as the property name, then this is not an issue, but worth raising just in case.
Here is a function that can do it recursivly:
function convertKey(obj) {
for (objKey in obj)
{
if (Array.isArray(obj[objKey])) {
convertKey[objKey].forEach(x => {
convertKey(x);
});
}
if (objKey === "Children") {
obj.children = obj.Children;
delete obj.Children;
}
}
}
And here is a more generic way for doing this:
function convertKey(obj, oldKey, newKey) {
for (objKey in obj)
{
if (Array.isArray(obj[objKey])) {
obj[objKey].forEach(objInArr => {
convertKey(objInArr);
});
}
if (objKey === oldKey) {
obj[newKey] = obj[oldKey];
delete obj[oldKey];
}
}
}
convertKey(json, "Children", "children");
Both the accepted answer, and #Tamas answer have slight issues.
With #Bardy's answer like he points out, there is the issue if any of your values's had the word Children it would cause problems.
With #Tamas, one issue is that any other properties apart from name & children get dropped. Also it assumes a Children property. And what if the children property is already children and not Children.
Using a slightly modified version of #Tamas, this should avoid the pitfalls.
function transform(node) {
if (node.Children) node.children = node.Children;
if (node.children) node.children = node.children.map(transform);
delete node.Children;
return node;
}
var json = {
"name": "a",
"Children": [{
"age": 13,
"name": "b",
"Children": [{
"name": "Mr Bob Chilren",
"Children": []
}, {
"name": "d",
"age": 33, //other props keep
"children": [{
"name": "already lowecased",
"age": 44,
"Children": [{
"name": "now back to upercased",
"age": 99
}]
}] //what if were alrady lowercased?
}]
}, {
"name": "e",
//"Children": [] //what if we have no children
}]
};
console.log(transform(json));

Compare two object arrays and combine missing objects

I have 2 object arrays. The 1st is an array of managers. The 2nd is an array of selected managers from the 1st array. The difference is I added a property selected: true. I need to now replace the the managers in the first array with selected managers. I am doing this with an AngularJS service I created. I'm sure there is much simpler solution so I'm open to suggestions. JavaScript, jQuery, lodash, LINQ.js are good.
I have a plunker and I have displayed the result I need. Notice the manager that does not have the selected:true property.
plunker
var app = angular.module("mainModule", []);
var MainController = function($scope, service) {
var eventUsers = [
{
"event_Users_ID":1009,"event_ID":11,"user_ID":"15e640c1-a481-4997-96a7-be2d7b3fcabb"
},{
"event_Users_ID":1010,"event_ID":11,"user_ID":"250a19be-e661-4c04-9a50-c84b0e7349b7"
},{
"event_Users_ID":1011,"event_ID":11,"user_ID":"4cada7f0-b961-422d-8cfe-4e96c1fc11dd"
},{
"event_Users_ID":1013,"event_ID":11,"user_ID":"a3125317-5deb-426d-bbb1-06d3bd4ebaa6"
}];
var managers = [
{
"id": "15e640c1-a481-4997-96a7-be2d7b3fcabb",
"fullName": "Kul Srivastva"
},{
"id": "250a19be-e661-4c04-9a50-c84b0e7349b7",
"fullName": "Todd Brothers"
}, {
"id": "4cada7f0-b961-422d-8cfe-4e96c1fc11dd",
"fullName": "Rudy Sanchez"
}, {
"id": "79823c6d-de52-4464-aa7e-a15949fb25fb",
"fullName": "Mike Piehota",
}, {
"id": "a3125317-5deb-426d-bbb1-06d3bd4ebaa6",
"fullName": "Nick Broadhurst"
}];
$scope.result = service.eventUserMatch(eventUsers, managers);
};
function service() {
var vm = this;
vm.eventUserMatch = function (eventUsers, managers) {
var arry = [];
arry = $.map(eventUsers, function (eventUser) {
var manager = $.grep(managers, function (user) {
return user.id === eventUser.user_ID;
})[0];
eventUser.id = manager.id;
eventUser.fullName = manager.fullName;
eventUser.selected = true;
return eventUser;
});
return arry;
};
}
app.controller("MainController", MainController);
app.service('service', service);
You can use Array#map.
// Get all the event user IDs in an array
var eventUserIds = eventUsers.map(e => e.user_ID);
// Iterate over managers
managers = managers.map(e => {
// If manager is present in the event users, `select` it
if (eventUserIds.indexOf(e.id) !== -1) {
e.selected = true;
}
return e;
});
var eventUsers = [{
"event_Users_ID": 1009,
"event_ID": 11,
"user_ID": "15e640c1-a481-4997-96a7-be2d7b3fcabb"
}, {
"event_Users_ID": 1010,
"event_ID": 11,
"user_ID": "250a19be-e661-4c04-9a50-c84b0e7349b7"
}, {
"event_Users_ID": 1011,
"event_ID": 11,
"user_ID": "4cada7f0-b961-422d-8cfe-4e96c1fc11dd"
}, {
"event_Users_ID": 1013,
"event_ID": 11,
"user_ID": "a3125317-5deb-426d-bbb1-06d3bd4ebaa6"
}];
var managers = [{
"id": "15e640c1-a481-4997-96a7-be2d7b3fcabb",
"fullName": "Kul Srivastva"
}, {
"id": "250a19be-e661-4c04-9a50-c84b0e7349b7",
"fullName": "Todd Brothers"
}, {
"id": "4cada7f0-b961-422d-8cfe-4e96c1fc11dd",
"fullName": "Rudy Sanchez"
}, {
"id": "79823c6d-de52-4464-aa7e-a15949fb25fb",
"fullName": "Mike Piehota",
}, {
"id": "a3125317-5deb-426d-bbb1-06d3bd4ebaa6",
"fullName": "Nick Broadhurst"
}];
var eventUserIds = eventUsers.map(e => e.user_ID);
managers = managers.map(e => {
if (eventUserIds.indexOf(e.id) !== -1) {
e.selected = true;
}
return e;
})
console.log(managers);
document.getElementById('result').innerHTML = JSON.stringify(managers, 0, 4);
<pre id="result"></pre>
would this work? Loop through the new array of managers, find the index using lodash of a matching manager object in the old manager array and replace it in the old manager array with the manager from the new manager array if found?
There's probably a more efficient way to write a solution to this but assuming I'm understanding your problem correctly I believe this should work? Can't test as I'm at work currently.
for(var i=0; i < SelectedManagersArray.length; i++){
var index = _.findIndex(OldManagersArray, {id: SelectedManagersArray[i].id, fullName: selectedManagersArray[i].fullName);
//I believe lodash returns a -1 if a matching index isn't found.
if(index !== -1){SelectedManagersArray[index] = OldManagersArray[i]}
}
Simple implementation:
for(var i = 0; i < eventUsers.length; i++) {
for(var j = 0; j < managers.length; j++) {
if(eventUsers[i].user_ID === managers[j].id) {
managers[j].selected = true;
}
}
}
As you said, I do think there may be an easier way to do this.
I advise you to pick a look to SugarJs which is a JavaScript library that extends native objects with so helpful methods.
In your case the doc on Arrays.
For me, it helps a lot dealing with a lot of native JavaScript Object (JSON).

javascript and json

I'm using javascript with a json library and running into a little trouble. Here's my json output:
{
"artist": {
"username": "myname",
"password": "password",
"portfolioName": "My Portfolio",
"birthday": "2010-07-12 17:24:36.104 EDT",
"firstName": "John",
"lastName": "Smith",
"receiveJunkMail": true,
"portfolios": [{
"entry": [{
"string": "Photos",
"utils.Portfolio": {
"name": "Photos",
"pics": [""]
}
},
{
"string": "Paintings",
"utils.Portfolio": {
"name": "Paintings",
"pics": [""]
}
}]
}]
}
}
In javascript I'm trying to access the entries in the map like so:
var portfolios = jsonObject.artist.portfolios.entry;
var portfolioCount = portfolios.length;
for ( var index = 0; index < portfolioCount; index++ )
{
var portfolio = portfolios[index];
txt=document.createTextNode("Portfolio Name: " + portfolio['string'] );
div = document.createElement("p");
div.appendChild ( txt );
console.appendChild(div);
}
but portfolios is "undefined". What's the correct way to do this?
Look at your JSON results. portfolios is a one-element array; portfolios[0] is an object containing a single key, entry, which maps to an array of two objects that have both string and utils.Portfolio keys. Thus, the syntax jsonObject.artist.portfolios.entry will not work. Instead, you want jsonObject.artist.portfolios[0].entry.
If possible, I would suggest changing whatever code generates those JSON results to remove the entry level of indirection entirely, e.g. like so:
{
"artist": {
/* ... */
"portfolios": [
{
"string": "Photos",
"utils.Portfolio": {
"name": "Photos",
"pics": [""]
}
},
{
"string": "Paintings",
"utils.Portfolio": {
"name": "Paintings",
"pics": [""]
}
}
]
}
}
Then you could access it with
var portfolios = jsonObject.artist.portfolios;
for (var i = 0, portfolio; portfolio = portfolios[i]; ++i)
{
// use portfolio variable here.
}
There is an array in your object. I believe you're looking for this:
var portfolios = jsonObject.artist.portfolios[0].entry;
The portfolios property is an array, so you need to use an index to get the first element:
var portfolios = jsonObject.artist.portfolios[0].entry;

Categories

Resources