Take Distinct values to populate Drop down - javascript

{ "Result": { "tags": [ { "name": "ABC", "email": "abc1#example.com", "sms": 123 }, {
"name": "ABC", "email": "abc2#example.com", "sms": 456 }, { "name": "ABC", "email":
"abc3#example.com", "sms": 789 }, { "name": "XYZ", "email": "xyz1#example.com", "sms": 976
}, { "name": "ABC", "email": "xyz2#example.com", "sms": 543 } ] } }
I have a JSON data like this. I want to Parse this JSON in PHP or Javascript to populate them in three drop downs.
Name | Email | SMS
But I need to Populate the distinct names in the dropdowns and populate email and sms based on selecting the name.
So far I just created the dropdowns.
Fiddle Link : http://jsfiddle.net/CAB2z/
Example:
Name should have : ABC | XYZ only once (Distinct : Should not repeat the same value).
When we select ABC, the three emails and phone numbers for "ABC" from the JSON should be populated in the second and third dropdown.

Try this,
$(function(){
var json = {
"Result": {
"tags": [{"name": "ABC","email": "abc1#example.com","sms": 123},
{"name": "ABC","email": "abc2#example.com","sms": 456},
{"name": "ABC","email":"abc3#example.com","sms": 789},
{"name": "XYZ","email": "xyz1#example.com","sms": 976},
{"name": "XYZ","email": "xyz2#example.com","sms": 543}]
}
};
var name = [],obj = {};
$(json.Result.tags).each(function (k, v) {
name[k] = (v.name);
obj[k] = {name: v.name,email: v.email,sms: v.sms};
});
$($.unique(name)).each(function (i, v) {
$('#name').append('<option value="'+v+'">'+v+'</option>');
});
$('#name').on('change', function () {
var $that = $(this);
$('#email').html('');$('#sms').html('');
$.each(obj,function (i, v) {
if( $that.val() == v.name) {
$('#email').append('<option value="'+v.email+'">'+v.email+'</option>');
$('#sms').append('<option value="'+v.sms+'">'+v.sms+'</option>');
}
});
}).change();
});
Live Demo

It will returns all results you want. Just append the vaues in
dropdown its your part.
var resultArray = r.Result.tags;
var unique = {};
var distinctName = [];
var email = [];
var sms = [];
for( var i in resultArray ){
if( typeof(unique[resultArray[i].name]) == "undefined"){
distinctName.push(resultArray[i].name); // push the unique names into the array
}
unique[resultArray[i].name] = 0;
email.push(resultArray[i].email); // push the email into the array
sms.push(resultArray[i].sms) // push the sms into the array
}
console.log(distinctName);
console.log(email);
console.log(sms);

In JavaScript, with jQuery, you can do:
var names, emails, smses;
(function() {
data = JSON.parse(data); // Get the data formatted.
var result = {
name: {},
email: {},
sms: {}
};
$.each(data.Result.tags, function(index, value) {
result.name [value.name] = true; // True won't be used, it can be any value.
result.email[value.email] = true;
result.sms [value.sms] = true
});
names = Object.keys(result.name);
emails = Object.keys(result.email);
smses = Object.keys(result.sms);
} ()); // Temporary variables (like result) are destroyed.
// names, emails and smses contain your data.

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 change multiple objects inside an array?

This is a two part question that I can't seem to solve. Part one requires that the entire object belonging to 'Theo' is removed somehow. Part two needs the object changed by editing one of the properties values belonging to 'Lorie'. Here's the array and instructions:
var employees = [{
"firstName": "Von",
"lastName": "Budibent",
"email": "vbudibent0#163.com",
"department": "Sales"
}, {
"firstName": "Catherina",
"lastName": "Swalowe",
"email": "cswalowe1#example.com",
"department": "Engineering"
}, {
"firstName": "Theo",
"lastName": "Trill",
"email": "ttrill2#sina.com.cn",
"department": "Services"
}, {
"firstName": "Elsy",
"lastName": "McCrorie",
"email": "emccrorie3#netscape.com",
"department": "Legal"
}, {
"firstName": "Lorie",
"lastName": "Handsheart",
"email": "lhandsheart4#fotki.com",
"department": "Research and Development"
}]
/* Create a function called 'employeeUpdater'. employeeUpdater will loop
over the array above and perform the following:
1. If employee's first name is Theo, remove that employee because he just
got fired.
2. If the employee's first name is Lorie, change her department to 'HR'.
3. Return the updated employee array. */
All I have to start is the following:
var employeeUpdater = () => {
for (let i = 0; i < employees.length; i++) {
if (employees[i] = 'Theo') {
employees.remove(employees[i]);
} else if (employees[i] = 'Lorie') {
employees.department = 'HR';
}
} return employees;
}
Something is wrong with the code
Javascript arrays don't have an method with name remove, instead you need to use Array#splice method for removing an item. But I can suggest this solution.
First use Array#filter to exclude the objects with name Theo then use Array#map or Array#forEach to iterate over the arrays an find the objects which name with Lorie and change it's department a.
var employees = [{
"firstName": "Von",
"lastName": "Budibent",
"email": "vbudibent0#163.com",
"department": "Sales"
}, {
"firstName": "Catherina",
"lastName": "Swalowe",
"email": "cswalowe1#example.com",
"department": "Engineering"
}, {
"firstName": "Theo",
"lastName": "Trill",
"email": "ttrill2#sina.com.cn",
"department": "Services"
}, {
"firstName": "Elsy",
"lastName": "McCrorie",
"email": "emccrorie3#netscape.com",
"department": "Legal"
}, {
"firstName": "Lorie",
"lastName": "Handsheart",
"email": "lhandsheart4#fotki.com",
"department": "Research and Development"
}];
var editedEmployees = employees
.filter(emp => emp.firstName !== 'Theo')
.map(emp =>
({
"firstName": emp.firstName,
"lastName": emp.lastName,
"email": emp.email,
"department": emp.firstName === 'Lorie' ? 'HR' : emp.department
}));
console.log(editedEmployees)
you can do it with splice():
var employeeUpdater = () => {
for (let i = 0; i < employees.length; i++) {
if (employees[i].firstName == 'Theo') {
employees.splice(i, 1);
i--;
} else if (employees[i].firstName == 'Lorie') {
employees[i].department = 'HR';
}
}
}return employees;
One of the tricky things about referencing objects in arrays is that you need to remember you have to reference them with the array index number and then the object name like employees[2].firstName would be how you reference Theo.
Also, the splice method is best for removing an array as stated above.
I believe the code you were trying to write would look like this:
var employeeUpdater = () => {
for (let i = 0; i < employees.length; i++) {
if (employees[i].firstName === 'Theo') {
employees.splice(i, 1);
} else if (employees[i].firstName === 'Lorie') {
employees[i].department = 'HR';
}
} return employees;
}
You should learn to program in an Object Oriented manner. Perhaps this will help:
//<![CDATA[
var pre = onload;
onload = function(){
if(pre)pre(); // change pre var name if using technique on other pages
var employees = [{
firstName:'Von',
lastName: 'Budibent',
email:'vbudibent0#163.com',
department:'Sales'
}, {
firstName:'Catherina',
lastName:'Swalowe',
email:'cswalowe1#example.com',
department:'Engineering'
}, {
firstName:'Theo',
lastName:'Trill',
email:'ttrill2#sina.com.cn',
department:'Services'
}, {
firstName:'Elsy',
lastName:'McCrorie',
email:'emccrorie3#netscape.com',
department:'Legal'
}, {
firstName:'Lorie',
lastName:'Handsheart',
email:'lhandsheart4#fotki.com',
department:'Research and Development'
}];
function EmployeeHandler(employeeArray){
this.employees = employeeArray;
this.removeByFirstName = function(firstName, caseSensitive){
var emp = this.employees;
var rx = caseSensitive ? new RegExp(firstName) : new RegExp(firstName, 'i');
for(var i=0,l=emp.length; i<l; i++){
if(emp[i].firstName.match(rx)){
this.employees.splice(i, 1);
return this;
}
}
return false;
}
this.removeByLastName = function(lastName, caseSensitive){
var emp = this.employees;
var rx = caseSensitive ? new RegExp(lastName) : new RegExp(lastName, 'i');
for(var i=0,l=emp.length; i<l; i++){
if(emp[i].lastName.match(rx)){
this.employees.splice(i, 1);
return this;
}
}
return false;
}
this.getByFirstName = function(firstName, caseSensitive){
var emp = this.employees;
var rx = caseSensitive ? new RegExp(firstName) : new RegExp(firstName, 'i');
for(var i=0,l=emp.length,em; i<l; i++){
em = emp[i];
if(em.firstName.match(rx)){
return em;
}
}
return false;
}
this.getByLastName = function(lastName, caseSensitive){
var emp = this.employees;
var rx = caseSensitive ? new RegExp(lastName) : new RegExp(lastName, 'i');
for(var i=0,l=emp.length,em; i<l; i++){
em = emp[i];
if(em.lastName.match(rx)){
return em;
}
}
return false;
}
}
var eh = new EmployeeHandler(employees);
var bb = eh.removeByFirstName('Theo').getByLastName('Budibent');
bb.department = 'Intelligent Design';
console.log(eh.employees); console.log(bb); console.log(eh.employees);
}
//]]>
Try this
var editedEmployees = employees
.filter(emp => emp.firstName !== 'Theo')
.map((emp) => {emp.department = emp.firstName === 'Lorie' ? 'HR' :
emp.department; return emp;});
If you like to work with lodash you can make your code easier to read.
So your script should become like this:
var _ = require('lodash');
/* Remove element */
_.remove(employees, function (employee) { return employee.firstName === 'Theo'; });
/* Get element to change */
var employee = _.find(employees,function (employee) { return employee.firstName === 'Lorie'; });
/* Change element */
employee.firstName = 'HR';
/* Right now employees store the right result */

How to read JSON using javascript?

I have JSON data like this -
var json = {
"details": [
{
"A": {
"Name": "mike",
"Age": 22
},
"B": {
"Name": "John",
"Age": 25
}
}
]
}
I want to read A,B points as an array.
Another way to do it with your json, Object.keys(),since your options are not in array form, can use that to convert to array form.
var json = {
"details": [
{
"A": {
"Name": "mike",
"Age": 22
},
"B": {
"Name": "John",
"Age": 25
}
}
]
}
var outputDiv = document.getElementById('output');
var options = Object.keys(json.details[0]).map(function(item){
return '<option value="'+item+'">'+ item +'</option>'
})
options.unshift('<option value="" > Please select </option>')
var select = document.getElementById('your_options');
select.innerHTML = options.join()
select.onchange = function() {
outputDiv.innerHTML = JSON.stringify(json.details[0][this.value]);
}
<label>You options</label>
<select id="your_options">
</select>
<div id="output"></div>
Lets assume you receive the following JSON from a web server
'{ "firstName":"Foo", "lastName":"Bar" }'
To access this data you first need to parse the raw JSON and form a Javascript object
let response = JSON.parse('{ "firstName":"Foo", "lastName":"Bar" }');
This forms an object which we can access relativly simply
let firstName = response["firstName"];
let lastName = response["lastName"];
Have a look at javascript documentation regarding JSON:
http://devdocs.io/javascript-json/
Examples:
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null

Create bar chart using mysql data

I want create bar using mysql data which is returned in JSON Format.
[
{
"Score": "84",
"Trainer": "Jamshaid",
"Subject Name": "Java"
},
{
"Score": "50",
"Trainer": "Zaid",
"Subject Name": "Android"
},
{
"Score": "40",
"Trainer": "Sajjad",
"Subject Name": "iOS"
},
{
"Score": "50",
"Trainer": "Jamshaid",
"Subject Name": "iOS"
}
]
I want to create like this chart
But problem is that this gets formatted from Table. But I have data in JSON as shown above.
Here is the link I am following. Can we convert the JSON Data in a Format so that it can populate chart based on the Data as shown
https://blueflame-software.com/bar-chart-with-data-from-mysql-using-highcharts/
You can process the JSON in the Javascript to build the data required for the chart as shown below:
var jsonFromServer = [
{
"Score": "84",
"Trainer": "Jamshaid",
"Subject Name": "Java"
},
{
"Score": "50",
"Trainer": "Zaid",
"Subject Name": "Android"
},
{
"Score": "40",
"Trainer": "Sajjad",
"Subject Name": "iOS"
},
{
"Score": "50",
"Trainer": "Jamshaid",
"Subject Name": "iOS"
}
];
The above is data from server captured in a variable
The below code helps you to extract the Y axis Values (i.e the unique subject names) from the JSON response:
function getSubjects(){
var subjectsMap = {};
$.each(jsonFromServer, function(index, value){
if(!subjectsMap[value['Subject Name']]){
subjectsMap[value['Subject Name']] = 1;
}
});
return $.map(subjectsMap, function(index, val){ return val; });
}
Then we need to extract the Scores for each trainer in different subject which should be of form: [{name: "Trainer", data: []}] where data is an array of scores in subject whose order should be same as the order of subjects appearing in the Y axis data. Which can be achieved using the below code:
function getTrainers(){
var trainersMap = {};
$.each(jsonFromServer, function(index, value){
if(!trainersMap[value['Trainer']]){
trainersMap[value['Trainer']] = 1;
}
});
return $.map(trainersMap, function(index, val){ return val; });
}
function getMarks(){
var subjects = getSubjects();
var trainers= getTrainers();
var marks = {};
//initialize the trainers scores in all subjects to 0
$.each(trainers, function(index, trainer){
if ( !marks[trainer]){
marks[trainer] = {};
}
$.each(subjects, function(idx2, sub){
marks[trainer][sub] = 0;
});
});
//now populate with the actual values obtained from server
$.each(subjects, function(idx2, sub){
$.each(jsonFromServer, function(index, value){
var trainer = value['Trainer'];
var subName = value['Subject Name'];
var score = value['Score'];
if ( sub == subName){
marks[trainer][sub] = score;
}
});
});
//now format the marks object into the format required for highcharts
//i.e an array of object with properties [{name: "", data:[]}]
return $.map(marks, function(val, index){
var scoreArray = [];
$.each(val, function(index, score){
scoreArray.push(parseInt(score));
});
return {"name": index, "data": scoreArray};
});
}
The working code can be found in the fiddle here.

How to transform JavaScript hashmap?

i'm trying to create a <String, Array()> map from a json object.
Imagine i got this json structure:
[
{
"userId": "123123",
"password": "fafafa",
"age": "21"
},
{
"userId": "321321",
"password": "nana123",
"age": "34"
}
]
The map i want to create would be:
key (string), value (array)
{
"userId": [
"123123",
"321321"
],
"password": [
"fafafa",
"nana123"
],
"age": [
"21",
"34"
]
}
Is it possible to do this? :/
Thanks in advance.
Demo
var json = '[{"userId" : "123123", "password": "fafafa", "age": "21"}, {"userId" : "321321", "password" : "nana123", "age" : "34"}]';
var list = JSON.parse(json);
var output = {};
for(var i=0; i<list.length; i++)
{
for(var key in list[i])
{
if(list[i].hasOwnProperty(key))
{
if(typeof output[key] == 'undefined')
{
output[key] = [];
}
output[key].push(list[i][key]);
}
}
}
document.write(JSON.stringify(output));
Outputs:
{"userId":["123123","321321"],"password":["fafafa","nana123"],"age":["21","34"]}
function mergeAttributes(arr) {
return arr.reduce(function(memo, obj) { // For each object in the input array.
Object.keys(obj).forEach(function(key) { // For each key in the object.
if (!(key in memo)) { memo[key] = []; } // Create an array the first time.
memo[key].push(obj[key]); // Add this property to the reduced object.
});
return memo;
}, {});
}
var json = '[{"userId" : "123123", "password": "fafafa", "age": "21"}, {"userId" : "321321", "password" : "nana123", "age" : "34"}]';
mergeAttributes(JSON.parse(json));
// {
// "userId": ["123123", "321321"],
// "password": ["fafafa", "nana123"],
// "age": ["21", "34"]
// }
Javascript's JSON.stringify will help you to convert any JSON compliant object model into a JSON string.

Categories

Resources