Create array of objects from ajax result - javascript

I am using DataTables with ajax and I am trying to dynamically generate a columns list as in the example here: https://datatables.net/examples/ajax/orthogonal-data.html (only in my case I have display and order for all items).
I tried with this approach, but this doesn't work and I am guessing push my sub values wrong.
Input (ajax result):
[{
"itemId": {
"order": "BG007002",
"display": "BG007002"
},
"builtDate": {
"order": "2000-03-01",
"display": "01.03.2000"
},
"openedDate": {
"order": "2005-07-09",
"display": "09.07.2005"
},
"buildingSize": {
"order": 15000,
"display": "15.000"
}
}, // ...
Expected output:
[
{ data: {
_: "itemId.display",
sort: "itemId.order"
}
},
{ data: {
_: "builtDate.display",
sort: "builtDate.order"
}
},
{ data: {
_: "openedDate.display",
sort: "openedDate.order"
}
},
{ data: {
_: "buildingSize.display",
sort: "buildingSize.order"
}
}
]
My approach:
var reportColsShort = $('#reportColsShort').text().slice(0,-1);
var aoCols = [];
var colss = reportColsShort.split(',');
for (var i = 0; i < reportColsShort.split(',').length; i++) {
var aoColss = {};
aoColss['data']['_'] = colss[i].display;
aoColss['data']['sort'] = colss[i].order;
aoCols.push(aoColss); // expected output
}
Error:
Cannot set property '_' of undefined.
Update:
Here is one more reference to what I am trying to achieve:
https://datatables.net/reference/option/columns.render#Examples

You can take the ajax result and then use a map see docs to structure your data like this:
const data = [{
"itemId": {
"order": "BG007002",
"display": "BG007002"
},
"builtDate": {
"order": "2000-03-01",
"display": "01.03.2000"
},
"openedDate": {
"order": "2005-07-09",
"display": "09.07.2005"
},
"buildingSize": {
"order": 15000,
"display": "15.000"
}
}];
const mapResult = data.map((elem) => {
let array = [];
Object.keys(elem).forEach((key) => {
const temp = {
data: {
_: elem[key].display,
sort: elem[key].order
}
}
array.push(temp);
});
return array;
});
console.log(mapResult);

Related

How can I apply pagination to a subobject in json-server?

I have a json-server with the following files:
db.json:
var faker = require('faker');
module.exports = function () {
var data = {
slack_users_list: slack_users_list(),
slack_users_info: slack_users_info()
}
return data;
}
function slack_users_list() {
const data = {
members: []
}
for (var i = 0; i < 10; i++) {
data.members.push({
id: "user_id_" + i
})
}
return data;
}
function slack_users_info() {
const data = {
user: []
}
for (var i = 0; i < 10; i++) {
data.user.push({
id: "user_id_" + i,
name: faker.internet.userName(),
team_id: faker.datatype.string(),
profile: {
title: faker.name.title(),
first_name: faker.name.firstName(),
last_name: faker.name.lastName(),
title: faker.name.title(),
email: faker.internet.email(),
phone: faker.phone.phoneNumber(),
skype: faker.internet.userName(),
},
})
}
return data;
}
And server.js:
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router(require('./db.js')())
const middlewares = jsonServer.defaults()
server.use(middlewares)
server.use(jsonServer.bodyParser)
// Wrap response depending on the object being called.
router.render = (req, res) => {
if (req.url.startsWith('/slack_users_list')) {
res.jsonp(res.locals.data)
} else if (req.url.startsWith('/slack_users_info')) {
param_user = req.query.user
if (param_user == null) {
res.jsonp({
"ok": false,
"error": "user_not_found"
})
return
}
user_list = res.locals.data.user
user_info = {}
for (var i = 0; i < user_list.length; i++) {
if (user_list[i].id == param_user) {
user_info = user_list[i]
}
}
res.jsonp({ user: user_info })
} else {
res.jsonp(res.locals.data)
}
}
server.use(router)
// Run server on indicated port.
server.listen(port = 3000, () => {
console.log('JSON Server is running')
console.log('http://localhost:' + port)
})
So when I call http://localhost:3000/slack_users_list I get:
{
"members": [
{
"id": "user_id_0"
},
{
"id": "user_id_1"
},
{
"id": "user_id_2"
},
{
"id": "user_id_3"
},
{
"id": "user_id_4"
},
{
"id": "user_id_5"
},
{
"id": "user_id_6"
},
{
"id": "user_id_7"
},
{
"id": "user_id_8"
},
{
"id": "user_id_9"
}
]
}
But if I want to apply pagination to it (e.g. http://localhost:3000/slack_users_list?_page=1&_limit=2), I get all the same objects, I assume because the pagination is getting applied to the first line of objects and not to each of the element inside members that get generated in db.json.
How can I modify this to apply the pagination on the sub-object members?
Thanks!
You can do the pagination right before sending the response.
// !!!
// This is just for demonstration.
// consider this req as the actual request.(req, res)
const req = {
params: { _page: '2', _limit:'3'}
}
// consider this as actual slack_users_list.members
const members = [
{
"id": "user_id_0"
},
{
"id": "user_id_1"
},
{
"id": "user_id_2"
},
{
"id": "user_id_3"
},
{
"id": "user_id_4"
},
{
"id": "user_id_5"
},
{
"id": "user_id_6"
},
{
"id": "user_id_7"
},
{
"id": "user_id_8"
},
{
"id": "user_id_9"
}
]
const page=Number(req.params._page)
const limit=Number(req.params._limit)
// paginating
const limited = members.slice((page - 1) * limit, page * limit)
console.log(limited)
// // send paginated response
//res.json(limited)

How to update array of objects based on key and values in Angular

I have below 3 objects listed below with data.
I want to find const oldData.data.parameter_value = b and oldData.data.label_value = b inside
each object of const newData.selected_parameter_value.
And if value exist in newData array, then replace all newData.selected_parameter_value.parameter_value = b and newData.selected_parameter_value.label_value = b , with const updatedData.data.parameter_value = red and const updatedData.data.label_value = red.
For ex -
const oldData = {
"action": "edit",
"data": {
"parameter_value": "b",
"label_value": "b"
}
};
const updatedData = {
"action": "update",
"data": {
"parameter_value": "red",
"label_value": "red"
}
};
const newData = [
{
"context": [],
"selected_parameter_value": [
{
"label_value": "a",
"parameter_value": "a"
},
{
"label_value": "b",
"parameter_value": "b"
}
]
},
{
"context": [],
"selected_parameter_value": [
{
"label_value": "b",
"parameter_value": "b"
}
]
}
];
Expected Output
const newData = [
{
"context": [],
"selected_parameter_value": [
{
"label_value": "a",
"parameter_value": "a"
},
{
"label_value": "red",
"parameter_value": "red"
}
]
},
{
"context": [],
"selected_parameter_value": [
{
"label_value": "red",
"parameter_value": "red"
}
]
}
];
Can Anyone help me to do this.
i tried below code but i dont know how to update matching objects in newData and keep all objects as it is.
editContextData(data) {
if (data.action === 'edit') {
this.oldData = data;
}
if (data.action === 'update') {
const oldData = this.oldData;
const updatedData = this.newData;
const newData = this.selectedParameterContext.records;
const newSelectedParameterContext = {
'records': []
};
newData.forEach(function (record) {
const newSelectedParameterValues = [];
record.selected_parameter_value.forEach(function (parameter) {
if(parameter.parameter_value === oldData.data.parameter_value && parameter.label_value === oldData.data.label_value){
// here i want to update object and push new values in array.
newSelectedParameterValues.push(updatedData);
}
});
newSelectedParameterContext.records.push({ 'selected_parameter_value': newSelectedParameterValues });
});
console.log(newSelectedParameterContext,"rrr");
this.selectedParameterContext = newSelectedParameterContext;
}
}
newData.forEach((item) => {
item.selected_parameter_value.forEach((obj) => {
if (oldData.data.parameter_value === obj.parameter_value) {
obj.parameter_value = updatedData.data.parameter_value;
}
if (oldData.data.label_value === obj.label_value) {
obj.label_value = updatedData.data.label_value;
}
})
Or if both have to be the same at the same moment then:
newData.forEach((item) => {
item.selected_parameter_value.forEach((obj) => {
if (oldData.data.parameter_value === obj.parameter_value && oldData.data.label_value === obj.label_value) {
obj.parameter_value = updatedData.data.parameter_value;
obj.label_value = updatedData.data.label_value;
}
});
});

How do I use a function inside another function's function

I am trying to capitalize the first letter of each word in the other function.
This is the function to turn each words first letter to capital that I am using.
function capital_letter(str)
{
str = str.split(" ");
for (var i = 0, x = str.length; i < x; i++) {
str[i] = str[i][0].toUpperCase() + str[i].substr(1);
}
return str.join(" ");
}
Here’s the second function that I’m trying to use the first one in, but it is not working.
$(document).ready(function() {
$('#list').dataTable({
"ajax":{
url :"list.php",
type: "GET",
error: function(){
$("#post_list_processing").css("display","none");
}
},
"columns": [
{ "data": function capital_letter(item) {
return item.title;
}
},
{ "data": "description" },
{ "data": "time" }
]
});
});
You should only call the function like the following:
$(document).ready(function() {
$('#list').dataTable({
ajax: {
url: 'list.php',
type: 'GET',
error: function() {
$('#post_list_processing').css('display', 'none');
},
},
columns: [{
data: capital_letter(item.title);
},
{ data: 'description' },
{ data: 'time' },
],
});
});
You're redefining the function instead of actually using it... Call it like this;
...
"columns": [
{ "data": capital_letter(item.title) }
...
You are not calling the function correctly. Change the following in your code.
"columns": [
{ "data": capital_letter(item.title) }
Created a working snippet.
function capital_letter(str) {
str = str.split(" ");
for (var i = 0, x = str.length; i < x; i++) {
str[i] = str[i][0].toUpperCase() + str[i].substr(1);
}
return str.join(" ");
}
const columns = [{
"data": capital_letter("abc")
},
{
"data": "description"
},
{
"data": "time"
}
]
console.log(columns)

Push entire subarray

I have an array this the format below. Trying to push multiple entire subarrays (starting with A-) fulfilling a condition to a new array and keep the array format. Have no success with the code below.
Array:
{"#VER": {
"A-1": {
"verdatum": "2016-07-08",
"vertext": "1073, Almi",
"trans": [{
"account": "1510",
"amount": "52500.00"
}, {
"account": "3010",
"amount": "-42000.00"
}, {
"account": "2611",
"amount": "-10500.00"
}]
},
"A-2": {
"verdatum": "2016-07-08",
"vertext": "1074, Text",
"trans": [{
"account": "1510",
"amount": "15000.00"
}, {
"account": "3010",
"amount": "-12000.00"
}, {
"account": "2611",
"amount": "-3000.00"
}]
}
}
}
Code so far, but changes format of array
var newarray = [];
$.each(array["#VER"], function(i, item) {
if (condition for subarray) {
newarray.push(i,item);
}
});
You're working with an object here, not an array. This code should work:
var data = { ... }; // your original data object
var filteredData = filterData(data);
function filterData(data) {
var verData = data['#VER'];
var filteredVerData = {};
$.each(verData, function(key, value) {
if(value.vertext === '1073, Almi') { // your condition
filteredVerData[key] = value;
}
});
return {
'#VER': filteredVerData
};
}
But if you have many root keys like '#VER' and you need to filter all of them, you'd need to write one more loop:
var data = { ... }; // your original data object
var filteredData = filterData(data);
function filterData(data) {
var result = {};
$.each(data, function(verKey, verData) {
$.each(verData, function(aKey, aData) {
if(aData.vertext === '1073, Almi') { // your condition
result[verKey] = result[verKey] || {};
result[verKey][aKey] = aData;
}
});
});
return result;
}

Transform JSON Object in AngularJs

Is there is a way to transform this JSON Object using Angular? I need to transform the JSON object from this format:
$scope.TestJson = {
"filters": [
{
"dataPropertyID": "VoidType",
"label": "Homeless"
},
{
"dataPropertyID": "VoidType",
"label": "Mainstream"
},
{
"dataPropertyID": "PropertyType",
"label": "Flat"
},
{
"dataPropertyID": "PropertyType",
"label": "Cottage"
}
]
}
To this format:
$scope.NewTestJson = {
"filters": [
{
"dataPropertyID": "VoidType",
"label":[ "Homeless","Mainstream"]
},
{
"dataPropertyID": "PropertyType",
"label":[ "Flat", "Cottage"]
}
]
}
I think this is more a JavaScript question than anything else. Nonetheless:
$scope.NewTestJson = {
filters: [];
};
// Do something for all (old) filter items
$scope.TestJson.filters.forEach(function(filter) {
// Try to get the existing (new) filter
var newFilter = $scope.NewTestJson.filters.filter(function(newFilter) {
return newFilter.dataPropertyID === filter.dataPropertyID;
}).shift();
// If the new filter does not exist, create it
if (!newFilter) {
newFilter = {
dataPropertyID: filter.dataPropertyID,
label: []
};
$scope.NewTestJson.filters.push(newFilter);
}
// Finally, add the old filter label to the new filter
newFilter.label.push(filter.label);
});
json = {
"filters": [
{
"dataPropertyID": "VoidType",
"label": "Homeless"
},
{
"dataPropertyID": "VoidType",
"label": "Mainstream"
},
{
"dataPropertyID": "PropertyType",
"label": "Flat"
},
{
"dataPropertyID": "PropertyType",
"label": "Cottage"
}
]
};
newJson = new Object();
newJson.filters = new Array();
for (var element in json.filters) {
var check = 0;
for (var element2 in newJson.filters) {
if (json.filters[element].dataPropertyID === newJson.filters[element2].dataPropertyID) {
newJson.filters[element2].label.push(json.filters[element].label);
check = 1;
}
}
if (check == 0) {
var Obj = new Object();
Obj.dataPropertyID = json.filters[element].dataPropertyID;
Obj.label = new Array();
Obj.label.push(json.filters[element].label);
newJson.filters.push(Obj);
}
}

Categories