Hi I am trying to create JSON using below code
test(array) {
var map = {};
var tt = [];
for(var i = 0; i < array.length; i++){
var obj = array[i];
var items = obj.items;
var child = Array.prototype.map.call(items, s => s.displayName);
map[obj.displayName] = {
child
};
}
return map;
}
Expected Response:
{
RoleManagement: [
'Create',
'Edit',
'Delete',
'Change permissions'],
UserManagement: [
'Create',
'Edit',
'Delete',
'Change permissions'
]
}
Error Response
Input Image
Input Response
https://i.stack.imgur.com/tYIoR.png
I Dont need child just array of create,update,delete
Please help me out
This is the place, you have done a mistake.
map["RoleManagement"] = {
child
};
For Example,Assume creating a new property "RoleManagement" inside the map object.
Based on you expected response, you wants to create a "RoleManagement" property, that contains array['Create','Edit','Delete','Change permissions'].
Instead, you are trying to create "RoleManagement" property as an object inside the map object.
Try this
//child contains the array
map["RoleManagement"] = child;
Here,You are initializing the property with array.
It Will solve your issue.
Related
I am taking data from a sheet and then converting it to json, so far all good. But when I am trying to take out specific data from arrays but it is making undefined if I get data from array, but when I use raw json data everything works fine
function doGet(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Users');
var userData = getUser(ss);
var array = userData.user.filter(function b(e) { return e.id == 11281 });
console.log(array)
}
function getUser(ss){
var usr = {};
var usrArray = [];
var data = ss.getRange(2,1,ss.getLastRow(), ss.getLastColumn()).getValues();
for (var i=0, l=data.length; i<l; i++){
var dataRow = data[i];
var record = {};
record['id'] = dataRow[1];
record['name'] = dataRow[0];
record['profession'] = dataRow[2];
usrArray.push(record);
}
usr.user = usrArray;
var result = JSON.stringify(usr);
return result;
}
ERROR: TypeError: Cannot read property 'filter' of undefined
Error picture
Sheet data picture
If I console log the result directly the it is working fine like this: Output
JSON.stringify returns a string — the getUser function returns a string. And you're trying to read the user property from it which returns undefined.
You could do a JSON.parse in doGet but it's simpler to just return the usr object from getUser.
function getUser(ss) {
const usr = {}
const usrArray = []
// populate usrArray
usr.user = usrArray
return usr
}
And there's another issue. You're setting record['id'] to dataRow[1] but it should be dataRow[0] since id is the first column (This is why the shared screenshot has the name in the id property). You could also refactor the code.
function getUser(ss) {
const data = ss
.getRange(2, 1, ss.getLastRow(), ss.getLastColumn())
.getValues()
const users = data.map((row) => ({
id: row[0],
name: row[1],
profession: row[2],
}))
return {
user: users,
}
}
I would also recommend renaming the user property to users for clarity.
I am working with the Wordpress REST API to retrieve some tags from a website. Maybe I haven't searched for the correctly on SO, but I am trying to get use my data and create my dataSet variable. But I am getting an error saying it's not recognizing the for loop token. I am quite new to Javascript so I don't know how to fix this.
Here is my code:
var req = new XMLHttpRequest();
var pieChart = document.getElementById('pie_chart_1');
req.open("GET", "http://example.org/wp-json/wp/v2/tags?per_page=10")
req.onload = function() {
if (req.status >= 200 && req.status < 400) {
var data = JSON.parse(req.responseText);
} else {
console.log("Returning an error");
}
};
req.onerror = function() {
console.log("Connection error");
};
req.send();
var dataSet = [
for(i = 0; i < data.length; i++) {
{legendLabel: data[i].name, magnitude:data[i].count, link: "http://example.com/tag" + data[i].slug},
}
];
You have a for loop inside the square brackets to define an array which is not syntactically correct. Since you are fetching tags using the WordPress REST API the response will be a JSON object with a tags property containing the results. It looks like you have a missing / in your link value as well.
Assuming this value for data.tags -
[{
display_name: 'Test Name',
slug: 'test-name',
}];
To properly use a for loop for this purpose -
const dataSet = [];
const tags = data.tags;
for (let i=0; i<tags.length; i+=1) {
dataSet.push({
legendLabel: tags[i].display_name,
link: "http://example.com/tag" + tags[i].slug,
});
}
A better way to create an array of JSON objects from your original array of JSON objects is to use Array.map() to "map" each element in the first array to a new element in a new array -
const dataSet = data.tags.map(function (element) {
return {
legendLabel: element.display_name,
link: "http://example.com/tag/" + element.slug,
};
});
Taking it further, you can use an arrow function, object parameter deconstruction, explicit return, string patterns, etc for more compact syntax with the same functionality -
const dataSet = data.tags.map(({ display_name: displayName, slug }) => ({
legendLabel: displayName,
link: `http://example.com/tag/${slug}`,
});
First of all, in most cases, it is better to use fetch API
In JS there is no for comprehensions so the last block of code could be refactored as follows:
const dataSet = data.map(({ name, count, slug }) => ({
legendLabel: name,
magnitude: count,
link: `http://example.com/tag${slug}`
}));
I have an empty javascript array(matrix) that I created to achieve refresh of divs. I created a function to dynamically put data in it. Then I created a function to update the Array (which I have issues).
The Data populated in the Array are data attributes that I put in a JSON file.
To better undertand, here are my data attributes which i put in json file:
var currentAge = $(this).data("age");
var currentDate = $(this).data("date");
var currentFullName = $(this).data("fullname");
var currentIDPerson = $(this).data("idPerson");
var currentGender = $(this).data("gender");
Creation of the array:
var arrayData = [];
Here is the function a created to initiate and addind element to the Array :
function initMatrix(p_currentIDPerson, p_currentGender, p_currentFullName, p_currentDate, p_currentAge) {
var isFound = false;
// search if the unique index match the ID of the HTML one
for (var i = 0; i < arrayData.length; i++) {
if(arrayData[i].idPerson== p_currentIDPerson) {
isFound = true;
}
}
// If it doesn't exist we add elements
if(isFound == false) {
var tempArray = [
{
currentIDPerson: p_currentIDPerson,
currentGender: p_currentGender,
currentFullName: p_currentFullName,
currentDate: p_currentDate, currentAge: p_currentAge
}
];
arrayData.push(tempArray);
}
}
The update function here is what I tried, but it doesn't work, maybe I'm not coding it the right way. If you can help please.
function updateMatrix(p_currentIDPerson, p_currentGender, p_currentFullName, p_currentDate, p_currentAge) {
for (var i = 0; i < arguments.length; i++) {
for (var key in arguments[i]) {
arrayData[i] = arguments[i][key];
}
}
}
To understand the '$this' and elm: elm is the clickableDivs where I put click event:
(function( $ ) {
// Plugin to manage clickable divs
$.fn.infoClickable = function() {
this.each(function() {
var elm = $( this );
//Call init function
initMatrixRefresh(elm.attr("idPerson"), elm.data("gender"), elm.data("fullname"), elm.data("date"), elm.data("age"));
//call function update
updateMatrix("idTest", "Alarme", "none", "10-02-17 08:20", 10);
// Définition de l'evenement click
elm.on("click", function(){});
});
}
$('.clickableDiv').infoClickable();
}( jQuery ));
Thank you in advance
Well... I would recommend you to use an object in which each key is a person id for keeping this list, instead of an array. This way you can write cleaner code that achieves the same results but with improved performance. For example:
var myDataCollection = {};
function initMatrix(p_currentIDPerson, p_currentGender, p_currentFullName, p_currentDate, p_currentAge) {
if (!myDataCollection[p_currentIDPerson]) {
myDataCollection[p_currentIDPerson] = {
currentIDPerson: p_currentIDPerson,
currentGender: p_currentGender,
currentFullName: p_currentFullName,
currentDate: p_currentDate,
currentAge: p_currentAge
};
}
}
function updateMatrix(p_currentIDPerson, p_currentGender, p_currentFullName, p_currentDate, p_currentAge) {
if (myDataCollection[p_currentIDPerson]) {
myDataCollection[p_currentIDPerson] = {
currentGender: p_currentGender,
currentFullName: p_currentFullName,
currentDate: p_currentDate,
currentAge: p_currentAge
};
}
}
Depending on your business logic, you can remove the if statements and keep only one function that adds the object when there is no object with the specified id and updates the object when there is one.
I think the shape of the resulting matrix is different than you think. Specifically, the matrix after init looks like [ [ {id, ...} ] ]. Your update function isn't looping enough. It seems like you are trying to create a data structure for storing and updating a list of users. I would recommend a flat list or an object indexed by userID since thats your lookup.
var userStorage = {}
// add/update users
userStorage[id] = {id:u_id};
// list of users
var users = Object.keys(users);
var oparea = [];
var mainarr_index = 0;
$("input.oparea-name").each(function(opera_key) {
var name_oparea = $(this);
oparea[mainarr_index]['maincat']['name'] = name_oparea.val(); //Add to array
$(subcats).each(function(index) {
oparea[mainarr_index]['subcat']['name'].push(name_subcat);
}
mainarr_index++;
}
The result I want:
oparea[0]['maincat']['name'] = 'name of oparea1';
oparea[0]['maincat']['subcat'] = array('name' => array('subcatname1', 'subcatname2'));
oparea[1]['maincat']['name'] = 'name of oparea2';
oparea[1]['maincat']['subcat'] = array('name' => array('subcatname1', 'subcatname2'));
//etc etc
The result I get in console is:
Uncaught TypeError: Cannot read property 'maincat' of undefined
Of course it's undefined, therefore I want to define it ;-)
How can I achieve what I want?
You can't set the property of an object if there's no object there to begin with. And you can't push onto an array if the array hasn't been created yet (I suspect you're used to PHP, which will fill these things in automatically when necessary).
And you can use .push to add the new object to the array, instead of using the oparea_index variable.
$("input.oparea-name").each(function(opera_key) {
var name_oparea = $(this);
var new_oparea = {
maincat: {
name: name_oparea.val()
},
subcat: {
name: []
}
};
$(subcats).each(function(index) {
new_oparea.subcat.name.push(name_subcat);
}
oparea.push(new_oparea);
}
var oparea = [];
$("input.oparea-name").each(function(opera_key) {
var name_oparea = $(this);
if(!oparea[mainarr_index]){
oparea[mainarr_index]={};
}
if(!oparea[mainarr_index]['maincat']){
oparea[mainarr_index]['maincat']={};
}
oparea[mainarr_index]['maincat']['name'] = name_oparea.val(); //Add to array
$(subcats).each(function(index) {
if(!oparea[mainarr_index]){
oparea[mainarr_index]={};
}
if(!oparea[mainarr_index]['subcat']){
oparea[mainarr_index]['subcat']={};
}
if(!oparea[mainarr_index]['subcat']['name']){
oparea[mainarr_index]['subcat']['name']=[];
}
oparea[mainarr_index]['subcat']['name'].push(name_subcat);
}
}
I'm fairly new to javascript. I retreive data from a sql server database that looks like this :
[Object { shortcode="0013A2004031AC9A", latest_measurement=1067, keyid="6801"},
Object { shortcode="0013A2004031AC9A", latest_measurement=7, keyid="6802"},
Object { shortcode="0013A2004031AC9A", latest_measurement=8598838, keyid="6803"}]
I want to format this in a json like this :
{mac : 0013A2004031AC9A, keys : {6801:1067, 6802:7, 6803:8598838}}
but I just don't get to that.
I have
var jsonDataPerMac = {};
I loop over the json object above and for every new mac I find I do :
jsonDataPerMac[i]={"mac": device.shortcode, "keys":[]};
but how do I get to fill the keys?
Any hints would be appreciated.enter code here
var macs = [];
var jsonDataPerMac = {};
var i = 0;
$.ajax({
url: "/bmmeasurements",
type: "GET",
data: {"unitid" : unitid},
async: false,
success: function (data) {
console.log(data);
initializeTable();
$.each(data, function (index,device) {
//add all distinct macs in an array, to use them as a column header
if($.inArray(device.shortcode, macs) == -1) {
macs.push(device.shortcode);
jsonDataPerMac[i]={"mac": device.shortcode, "keys":[]};
i++;
//create a table cell for each possible key. id = 'mac-key'
createTableGrid(device.shortcode);
}
//add the measurement data to the correct cell in the grid
$('#' + device.shortcode + '-' + device.keyid).html(device.latest_measurement);
});
}});
Here is my proposition. I would rather avoid using jQuery to perform such a simple operations. In this particular example, we use forEach and for..in loop.
//new output array
var newArray = [];
//we traverse the array received from AJAX call
array.forEach(function(el) {
var added = false; // it's false by default
// we check if the mac is already in newArray, if yes - just add the key
for(var i in newArray) {
if(newArray[i].mac == el.shortcode) {
newArray[i].keys.push(el.keyid+":"+el.latest_measurement);
added = true; // tells us whether the key has been added or not
}
}
// if key hasn't been added - create a new entry
if(!added) {
newArray.push({"mac": el.shortcode, "keys":[el.keyid+":"+el.latest_measurement]});
}
});
console.log(newArray);
You can transform above code to a function and then, reuse it in your ajax onSuccess method. Remember to pass the array as an argument and to return newArray.
JSFiddle:
http://jsfiddle.net/2d5Vq/2/
You need to combine the entries first...
var reducedData = {};
$.each(macs, function(index,macitem){
if (reducedData.hasOwnProperty(macitem.shortcode)) {
reducedData[macitem.shortcode].push(macitem.key);
} else {
reducedData[macitem.shortcode] = [ macitem.key ];
}
});
And then map to your desired format inside an array...
var jsonDataPerMac = [],
i = 0;
$.map(reducedData, function(keys,mac){
jsonDataPerMac[i++] = {"mac": mac, "keys": keys};
// your other code goes here
});
Also your usage of jsonDataPerMac suggests that you want it to be an array.