Mapping Key value pair to javascript Object - javascript

I wanted to map data from the service call to java script object for same javascript object will be passed to the chart api
The single data format of the javascript array should be like this
var val2 = {
label: 'Data Seg2',
data: [[0, 10]]
};
it can have multiple data values also like this
var val3 = {
label: 'Data Seg2',
data: [[0, 10], [1, 20],[2, 30],[3, 40],[4, 50]]
};
Tha main Array looks like this
var datatest = [{
label: 'First Label',
data: [[0, 30]]
}, {
label: 'Second Label',
data: [[0, 20]]
}, {
label: 'Third Label',
data: [[0, 50]]
}, {
label: 'Fourth Label',
data: [[0, 10]]
}];
Now i have the service all result like this.
{"d":"[{\"label\":\"Lable1\",\"data\":[{\"Key\":\"0\",\"Value\":\"108859\"}]},{\"label\":\"Lable2\",\"data\":[{\"Key\":\"0\",\"Value\":\"20493248.94\"}]},{\"label\":\"Label3\",\"data\":[{\"Key\":\"0\",\"Value\":\"1195\"}]}]"}
Now i want to map this result to "datatest" format
How can i do this ?
Thanks in advance

You could use jQuery.map() function like this:
var serverJSON = {"d":"[{\"label\":\"Lable1\",\"data\":[{\"Key\":\"0\",\"Value\":\"108859\"}]},{\"label\":\"Lable2\",\"data\":[{\"Key\":\"0\",\"Value\":\"20493248.94\"}]},{\"label\":\"Label3\",\"data\":[{\"Key\":\"0\",\"Value\":\"1195\"}]}]"};
var serverData = JSON.parse(serverJSON.d);
var datatest= $.map(serverData, function(arrayItem) {
return {
label: arrayItem.label,
data: $.map(arrayItem.data, function(dataItem) {
return [[parseFloat(dataItem.Key), parseFloat(dataItem.Value)]];
})
};
});
Result is :
[{"label":"Lable1","data":[[0,108859]]},{"label":"Lable2","data":[[0,20493248.94]]},{"label":"Label3","data":[[0,1195]]}]
Working demo.

You data is a little bit strange, anyway...
var rawData = {"d":"[{\"label\":\"Lable1\",\"data\":[{\"Key\":\"0\",\"Value\":\"108859\"}]},{\"label\":\"Lable2\",\"data\":[{\"Key\":\"0\",\"Value\":\"20493248.94\"}]},{\"label\":\"Label3\",\"data\":[{\"Key\":\"0\",\"Value\":\"1195\"}]}]"};
var dataSet = JSON.parse(rawData.d);
var fn = function(data){
data.data = data.data.map(function(d){
return [d.Key, d.Value];
});
return data;
};
var newSet = dataSet.map(fn); // what you want
Result:
[
{
"label": "Lable1",
"data": [
[
"0",
"108859"
]
]
},
{
"label": "Lable2",
"data": [
[
"0",
"20493248.94"
]
]
},
{
"label": "Label3",
"data": [
[
"0",
"1195"
]
]
}
]
It will do the trick. Not sure if there is other elegant way to do so.
PS: it is recommended to format your json string first via http://jsonformat.com/ or so

with pure JavaScript you can do this:
mapthis = {"d":"[{\"label\":\"Lable1\",\"data\":[{\"Key\":\"0\",\"Value\":\"108859\"}]},{\"label\":\"Lable2\",\"data\":[{\"Key\":\"0\",\"Value\":\"20493248.94\"}, {\"Key\":\"1\",\"Value\":\"1111111.94\"}]},{\"label\":\"Label3\",\"data\":[{\"Key\":\"0\",\"Value\":\"1195\"}]}]"};
var x = eval(mapthis.d);
var newdatatest = [];
for(var i=0; i<x.length; i++){
var datas = [];
for(var j=0; j<x[i].data.length;j++){
datas.push([x[i].data[j].Key, x[i].data[j].Value]);
}
newdatatest.push( {label:x[i].label, data:datas} );
}
console.log(JSON.stringify(newdatatest,null,2));
Results:
[
{
"label": "Lable1",
"data": [
[
"0",
"108859"
]
]
},
{
"label": "Lable2",
"data": [
[
"0",
"20493248.94"
],
[
"1",
"1111111.94"
]
]
},
{
"label": "Label3",
"data": [
[
"0",
"1195"
]
]
}
]

Related

how to foreach array to array object in javascript

I'm very confused about doing foreach array to array object in Javascript, I already did a lot of research about foreach object in Javascript and I tried many ways but nothing works. All that I'm trying to achieve is to have data JSON like this :
[
{
"name": "First Data",
"data": [
{
"y": 95,
"total":100,
"md": "1",
"name": "National",
"drillup" : 'level0',
"drilldown" : "3",
"next" : "level2"
}
]
}
,{
"name": "Second Data",
"data": [
{
"y": 95,
"total":100,
"md": "1",
"name": "National",
"drillup" : 'National',
"drilldown" : "3",
"next" : "level2"
}
]
}
]
and I tried to do foreach based on some finding of my research but the result wasn't like what I want or like what I'm try to achieve ..
and here is the script that I tried :
dataFirstSecond = await informationModel.getdata();
Object.entries(dataRegularSecondary).forEach(entry => {
const [key, value] = entry;
returnData[key] = [
{
name: value.name,
data: [{
y: value.y,
total: value.total_ada,
next: 'level_2',
drilldown: true,
}]
}]
});
and here is the result or the output of my script that I try it :
{
"0": [
{
"name": "First Data",
"data": [
{
"y": 22.973,
"total": 17,
"next": "level_2",
"drilldown": true
}
]
}
],
"1": [
{
"name": "Second Data",
"data": [
{
"y": 5.4054,
"total": 4,
"next": "level_2",
"drilldown": true
}
]
}
]
}
can someone help me to achieve the data that I want?
returnData[key] = [{ ... }] should just be returnData.push({ ... }), and make sure returnData is an array (e.g. returnData = [])
If the function informationModel.getdata(); returns an Object you could use the method JSON.stringify(Object) to easily convert and Object to JSON. For example you could try to do to convert this Object to a String then cast the String to JSON.
let JSONString = JSON.stringify(informationModel.getdata());
let JSON_Object = JSON.parse(JSONString);
If dataRegularSecondary is an array and not an object you could use map:
dataRegularSecondary.map(value => {
return {
name: value.name,
data: [{
y: value.y,
total: value.total_ada,
next: 'level_2',
drilldown: true,
}]
}
}
Your question is how to forEach array to array object. Then that means dataRegularSecondary is an array, right? Object.entries returns an array of key value pairs. If you pass an array to that method, it will return the indices as keys and the items as values.
const arr = ['hello', 'world'];
Object.entries(arr); // [['0', 'hello'], ['1', 'world']]
Skip the Object.entries and use dataRegularSecondary directly for forEach.
As for your output, it looks like returnData is an object as well. Make sure it's an array and just push the data into that.
dataRegularSecondary.forEach(value => {
returnData.push({
name: value.name,
data: [{
y: value.y,
total: value.total_ada,
next: 'level_2',
drilldown: true,
}],
});
});
Or you can use map as well.
const returnData = dataRegularSecondary.map(value => ({
name: value.name,
data: [{
y: value.y,
total: value.total_ada,
next: 'level_2',
drilldown: true,
}],
}));

How to convert nested array of object into arraylist in javascript?

i have a nested array of object and i want to convert in arraylist like this :
this is my data array of object :
{
"status": true,
"message": "",
"data": [{
"pasien_docs": [{
"ecg": null,
"date": "2020-01-21T05:22:01.901Z"
}, {
"ecg": 1.03,
"date": "2020-01-21T05:22:02.979Z"
}, {
"ecg": 1.04,
"date": "2020-01-21T05:22:04.053Z"
}, {
"ecg": 1.04,
"date": "2020-01-21T05:22:05.126Z"
},
]
}
]
}
and i want change convert to array like this :
{
"status": true,
"message": "",
"data": [
[
"2020-01-21T05:22:01.901Z",
null
],
[
"2020-01-21T05:22:01.901Z",
1, 03
]
[
"2020-01-21T05:22:01.901Z",
1.04
]
[
"2020-01-21T05:22:01.901Z",
1.04
]
]
}
i try using map to convert on result like this :
result = result.map((u, i) => [
u.pasien_docs[i].date,
u.pasien_docs[i].ecg,
]);
but why i only get result data of one array not four data ? help me please, thankyou..
{
"status": true,
"message": "",
"data": [
[
"2020-01-21T05:22:01.901Z",
null
]
]
}
Would that work for you?
const src = {"status":true,"message":"","data":[{"pasien_docs":[{"ecg":null,"date":"2020-01-21T05:22:01.901Z"},{"ecg":1.03,"date":"2020-01-21T05:22:02.979Z"},{"ecg":1.04,"date":"2020-01-21T05:22:04.053Z"},{"ecg":1.04,"date":"2020-01-21T05:22:05.126Z"},]}]},
result = {
...src,
data: src.data[0].pasien_docs.map(Object.values)
}
console.log(result)
.as-console-wrapper{min-height:100%;}
If you dont wanna use spread operator, this can also do the trick for you
const source = {"status":true,"message":"","data":[{"pasien_docs":[{"ecg":null,"date":"2020-01-21T05:22:01.901Z"},{"ecg":1.03,"date":"2020-01-21T05:22:02.979Z"},{"ecg":1.04,"date":"2020-01-21T05:22:04.053Z"},{"ecg":1.04,"date":"2020-01-21T05:22:05.126Z"},]}]}
const result = Object.assign({}, source, {
data: source.data[0].pasien_docs.map(Object.values)
})
console.log(result)
let obj = {
status: true,
message: "",
data: [
{
pasien_docs: [
{
ecg: null,
date: "2020-01-21T05:22:01.901Z",
},
{
ecg: 1.03,
date: "2020-01-21T05:22:02.979Z",
},
{
ecg: 1.04,
date: "2020-01-21T05:22:04.053Z",
},
{
ecg: 1.04,
date: "2020-01-21T05:22:05.126Z",
},
],
},
],
};
var finalobj = JSON.parse(JSON.stringify(obj));
var innerobj = obj.data;
var intermd = innerobj.map((data) => {
return data.pasien_docs;
});
finalarray = intermd[0].map((val) => {
return [val.ecg, val.date];
});
console.log(obj);
finalobj.data[0].pasien_docs=finalarray;
console.log(finalobj);

Show key as value in datatable

Hi I'm currently having trouble with datatable. My datasource is object and I want every first key in the object displayed as value in datatable. Here is my code.
var my_data = {
"content": [
{
"data_v1": [{"id" : 1}]
},
{
"data_v2": [{"id" : 2}]
},
{
"data_v3": [{"id" : 3}]
}
]
};
$(document).ready(function() {
$('#example').DataTable( {
data:my_data,
columns: [
{ data: 'content'
}
]
} );
} );
What output I expect is this.
| Content |
-------------
data_v1
data_v2
data_v3
Note: As long as posible, I don't want to use forloop or any kind of loop. TIA
Any help will be so much appreciated.
Try
var myData = {
"content": [
{
"data_v1": [{"id" : 1}]
},
{
"data_v2": [{"id" : 2}]
},
{
"data_v3": [{"id" : 3}]
}
]
};
$(document).ready(function()
{
$('#example').DataTable( {
data: Object.keys(myData["content"]),
columns: [
{ title: 'content'
}
]
});
});
Object.keys will return an array of keys from the data provided
This answer is from #colin of Datatable.
$(document).ready(function() {
var my_data = {
"contents": [{
"data_v1": [{
"id": 1
}]
},
{
"data_v2": [{
"id": 2
}]
},
{
"data_v3": [{
"id": 3
}]
}
]
};
var table = $('#example').DataTable({
data: my_data.contents,
columnDefs: [{
targets: 0,
render: function(data, type, row, meta) {
return (Object.keys(row)[0]);
}
}]
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<link href="//cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet"/>
<table id="example"></table>

modify json object and save it

I do have a json array object. I need to modify it then save the modified version on a variable.
the json object
var json = [
{
"Name": "March-2016",
"Elements": [
{
"Name": "aa",
"Elements": [
{
"Name": "ss",
"Data": {
"Test1": [
22
],
"Test2": [
33
],
"Test3": [
44
],
"Test4": [
55
]
}
},
{
"Name": "ssee",
"Data": {
"Test12": [
222
],
"Test22": [
3322
],
"Test32": [
445
],
"Test42": [
553
]
}
}
]
}
]
}
];
need to be modified to
var json = [
{
"Name": "March-2016",
"Elements": [
{
"Name": "aa",
"Elements": [
{
"category": "ss",
"Test1": 22,
"Test2": 33 ,
"Test3":44,
"Test4": 55
},
{
"category": "ssee",
"Test12": 222,
"Test22": 3322 ,
"Test32":445,
"Test42": 553
}
]
}
]
}
];
I have this method but its not doing the job
var saveJson = function(arr) {
var nameValuePairs = [];
for (var i = 0, len = arr.length; i < len; i++) {
var item = arr[i];
if (item.Data) {
var newvar = {
category : item.Name
}
newvar[Object.keys(item.Data)] = Object.values(item.Data);
item = newvar
}
if (item.Elements) {
nameValuePairs = nameValuePairs.concat(saveJson(item.Elements));
}
}
return arr;
};
I need this conversion to be dynamic as for sure I will get bigger json than the posted one
sorry for the confusion and thanks in advance.
The original object is really a mess, but still you just need to step through it and pull out the values you want. This changes the json object in place:
json.forEach(item => {
item.Elements.forEach(Outer_El => {
Outer_El.Elements = Outer_El.Elements.map(item =>{
let obj = {category: item.Name}
Object.keys(item.Data).forEach(key => {
obj[key] = item.Data[key][0]
})
return obj
})
})
})
json should now look like:
[{
"Name":"March-2016",
"Elements":[
{
"Name":"aa",
"Elements":[
{
"category":"ss",
"Test1":22,
"Test2":33,
"Test3":44,
"Test4":55
},
{
"category":"ssee",
"Test1e":224,
"Test2e":334,
"Test3e":443,
"Test4e":554
}
]
}
]
}]
You can use destructuring assignment to get specific property values from an object
{
let {Name:categories, Data:{Test:[Test]}} = json[0].Elements[0].Elements[0];
json[0].Elements[0].Elements[0] = {categories, Test};
}

How can I flatten nested arrays in JavaScript?

I have complicated array with nested arrays.
For example if I want to get data from last array then I have to write:
partners[0].products[0].campaigns[0].nameCampaign or .type or .price etc.
I'd like to flatten this array. And this is what I expect:
Is it possible at all?
#EDIT
This is part of console.log(JSON.stringify(partners, 0, 4));:
[{
"_id": "57727902d0a069e41a34eece",
"namePartner": "Self",
"products": [{
"_id": "57727910d0a069e41a34eed0",
"nameProduct": "Singl",
"campaigns": [{
"_id": "57727937d0a069e41a34eed1",
"type": "lead",
"nameCampaign": "Camp 0"
}]
}, {
"_id": "5774cb68c594b22815643b37",
"nameProduct": "DrugiPartner"
"campaigns": [{
"_id": "5774cb78c594b22815643b38",
"type": "subscription",
"nameCampaign": "DrugaKampania"
}, {
"_id": "5774cbedc594b22815643b3a",
"type": "subscription",
"nameCampaign": "TrzeciaKampania"
}, {
"_id": "5774cbf9c594b22815643b3b",
"type": "subscription",
"nameCampaign": "CzwartaKampania"
}]
}, {
"_id": "5774cbdbc594b22815643b39",
"nameProduct": "Trzeci"
"campaigns": []
}]
}]
In plain Javascript you could use an array with the references to the wanted items and the arrays and use an iterative recursive approach to get the wanted array.
Edit
For more than one property to add, you could use an array for more than one item.
One property:
{ use: 'namePartner' }
Multiple properties:
{ use: ['nameCampains', 'type'] }
function iter(a, r, l) {
if (Array.isArray(a)) {
a.forEach(function (b) {
var use = level[l].use,
rr = JSON.parse(JSON.stringify(r));
(Array.isArray(use) && use || [use]).forEach(function (c) {
rr[c] = b[c];
});
iter(b[level[l].array], rr, l + 1);
});
return;
}
result.push(r);
}
var partners = [{ namePartner: 'Tesco', products: [{ nameProduct: 'New', campains: [{ nameCampains: 'Apple', type: 'appleType' }, { nameCampains: 'Lenovo', type: 'lenovoType' }] }] }, { namePartner: 'Eko', products: [{ nameProduct: 'Fresh', campains: [{ nameCampains: 'Asus', type: 'asusType' }, { nameCampains: 'Dell', type: 'dellType' }] }, { nameProduct: 'new', campains: [{ nameCampains: 'Samsung', type: 'samsungType' }] }] }],
level = [{ use: 'namePartner', array: 'products' }, { use: 'nameProduct', array: 'campains' }, { use: ['nameCampains', 'type'] }],
result = [];
iter(partners, {}, 0);
console.log(result);
You could use get from lodash:
var CAMPAIGN_NAME_PATH = ['partners', 0, 'products', 0, 'campaigns', 0, 'nameCampaig'];
var campaignName = _.get(JSONObject, CAMPAIGN_NAME_PATH, 'optionalDefaultCampaignName');
Or you could try playing with flatten, flattenDeep and flattenDepth and rearrange the JSON object structure first before accessing it (note that these three methods only work on arrays, not key-value objects).

Categories

Resources