JSON to object array format - javascript

I want to display like convert JSON data to array objects how can solve this problem using jquery or js?
JSON data :
[{
"new": 122,
"old": 3389,
"boarding": 1,
"aws": 10,
"azure": 12,
"cli": 41
}];
To array object:
[
["new", 122],
["old", 3389],
["boarding", 1]
]
one more pattern I need it I have an array like this in Ruby
[37,
3,
261,
1,
0,
1457]
to convert into add as key entry static
[
["new",37],
["old",3],
["boarding",1]
["aws",0]
["azure",1457]
]

Firstly note that you do not need jQuery at all for this. jQuery is primarily a tool for amending the DOM. To work with data structures like this native JS is all you need.
To achieve what you require, you can use Object.keys() to get the keys of the 0th object in your original array, then you can loop over them using map() to build a new 2 dimensional array from that data:
var originalArr = [{
"new": 122,
"old": 3389,
"boarding": 1,
"aws": 10,
"azure": 12,
"cli": 41
}];
var newArr = Object.keys(originalArr[0]).map(function(key) {
return [key, originalArr[0][key]];
});
console.log(newArr);

Its simple enough. Just enter the array into Object.entries(). like this Object.entries(originalArr[0])

A simple one-line alternative:
const data = [{
"new": 122,
"old": 3389,
"boarding": 1,
"aws": 10,
"azure": 12,
"cli": 41
}];
const result = Object.keys(data[0]).map(k => ([k, data[0][k]]));
console.log(result);

Related

Nodejs Multiple map arrays to single Json file

I'm new to nodejs and am trying to write a Json parser that will take data from a Json API, allow me to grab the data I want (some of this data I will transform) and then write to a Json file.
I have discovered the map command which is extracting the raw data and this is giving me an array for example
data['home_team'] = json['data'].map(smdata => smdata.localTeam.data.name);
data['awayid'] = json['data'].map(smdata => smdata.visitorTeam.data.id);
data['away_team'] = json['data'].map(smdata => smdata.visitorTeam.data.name);
And this works perfectly, now I'm left with an array which I want to turn into a Json file, I can of course just run a FOR loop and iterate through each of the entries and write to a file but I wondered if there was a more efficent way to do this
Thanks
Take a look at JSON.stringify to turn your data into a string you can write to a file.
In your comments below, you provide an invalid JS structure, an array with keys - maybe a typo with square braces (array) rather than curly braces (object). Or maybe note that Array map returns an array, so you may wish to look at Array.reduce, depending on your data.
let data = {
islive: [90, 90, null, null],
ls: [1, 1, 1, 1],
time: [90, 90, null, null],
status: ['FT', 'FT', 'NS', 'NS'],
starttime: [1616036700, 1616050800, 1616058000, 1616058900],
matchid: [17706353, 17926675, 17869155, 17926676]
};
// Dump it as JSON:
console.log(JSON.stringify(data));
// Pretty print with 2 space indent:
console.log(JSON.stringify(data, {}, 2));
// Write it to file 'my.json':
const fs = require('fs');
fs.writeFileSync(
'my.json',
JSON.stringify(data)
);
Outputs:
{"islive":[90,90,null,null],"ls":[1,1,1,1],"time":[90,90,null,null],"status":["FT","FT","NS","NS"],"starttime":[1616036700,1616050800,1616058000,1616058900],"matchid":[17706353,17926675,17869155,17926676]}
{
"islive": [
90,
90,
null,
null
],
"ls": [
1,
1,
1,
1
],
"time": [
90,
90,
null,
null
],
"status": [
"FT",
"FT",
"NS",
"NS"
],
"starttime": [
1616036700,
1616050800,
1616058000,
1616058900
],
"matchid": [
17706353,
17926675,
17869155,
17926676
]
}

How to rename properties in objects that are in an array. What is the right way to solve the task?

I need to build diagram,
There is an array with objects for chart data
"graphicDetails": [
{
"hour": 0,
"businessOperationPlansTotalDemand": 8.201753196882908,
"employeesCount": 0,
"businessOperationPlans": [
{
"name": "operation0",
"value": 5.999355066255491
},
]
},
{
"hour": 1,
"businessOperationPlansTotalDemand": 7.450044665662842,
"employeesCount": 3,
"businessOperationPlans": []
},
{
"hour": 2,
"businessOperationPlansTotalDemand": 5.814536267254451,
"employeesCount": 5,
....
To draw it in the chart library (chartjs) I need the object to be with the fields {x: hour, y: businessOperationPlansTotalDemand, etc.}. Example:
data: [
{ x: 0, y: 5.815634, businessOperationPlans: [{operation: ...}] ,
{ x: 1, y: 2.23232, businessOperationPlans: [{operation2: ...}] ,
...
]
I know i can use forEach or something like this to rename properties, but what is the right way to resolve this task? maybe i should ask backend to make data in other format?
Maybe I need to create a new array based on this with other properties and put it in the computed field in Vue? How can i do this?
You can use map
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
const graphicDetails = [{
"hour": 0,
"businessOperationPlansTotalDemand": 8.201753196882908,
"employeesCount": 0,
"businessOperationPlans": [{
"name": "operation0",
"value": 5.999355066255491
}, ]
},
{
"hour": 1,
"businessOperationPlansTotalDemand": 7.450044665662842,
"employeesCount": 3,
"businessOperationPlans": []
}
];
const newData = graphicDetails.map(a=>{
return {x:a.hour,y:a.businessOperationPlansTotalDemand,businessOperationPlans:a.businessOperationPlans };
})
console.log(newData);
You can create a new array and design as per your new array structure . If you are using any backend , create the structure from there and process the same in computed , rather put it in mounted so it will load the same in the component gets mounted . Best way will be to process the data-set from backend .

map an array from an array of objects key/value

I need to take an array objects that and map it so that the new array is just a simple array if each object's id.
So for example:
[
{id: 49, name: "Rest update test"},
{id: 12, name: "Rest test"}
]
would become:
[49, 12]
i have tried this so far:
myObject.map(object => object.id);
so my actual function that is not working is the following, when I view the console.log, it is showing the original object:
onSubmit() {
this.userForm.value.accountsToAdd.map(object => object.id);
console.log(this.userForm.value.accountsToAdd);
}
Assuming the given code does not work, then you need to assign the result of mapping.
Array#map does not mutate the original array but return a new one.
var array = [{ id: 49, name: "Rest update test" }, { id: 12, name: "Rest test" }],
ids = array.map(object => object.id);
console.log(ids);

Reading CSV in D3 and converting it to array of arrays

I have the following small dataset hardcoded into a variable in my code:
var dataset = [['CENTRAL', 44, 552, 18565],
['NORTHERN', 42, 945, 20092],
['SOUTHERN', 96, 795, 30095],
['PARK', 1, 640, 9341],
['MISSION', 66, 1198, 18542],
['TENDERLOIN', 23, 113, 10735],
['RICHMOND', 9, 561, 9082],
['TARAVAL', 81, 789, 11966],
['INGLESIDE', 5, 1368, 13414],
['BAYVIEW', 7, 985, 14711]];
Now, this dataset is taken directly from a .csv file, that looks like this:
District,Prostitution,VehicleTheft,Totalcrimecount
CENTRAL,44,552,18565
NORTHERN,42,945,20092
SOUTHERN,96,795,30095
PARK,1,640,9341
MISSION,66,1198,18542
TENDERLOIN,23,113,10735
RICHMOND,9,561,9082
TARAVAL,81,789,11966
INGLESIDE,5,1368,13414
BAYVIEW,7,985,14711
However, I'd obviously like to be able to just read in the file, which I've attempted using this:
var dataset_csv = d3.csv("datafile.csv", function(d){
console.log(dataset_csv = d)
});
Which gives me an array of objects that look like this:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
District: "CENTRAL"
Prostitution: "44"
Totalcrimecount: "18565"
VehicleTheft: "552"
My question is, and it might be trivial, how can I transform those objects into an array data structure like my initial dataset? I've been battling with it for some time now. Any hints greatly appreciated.
Use Array#map to iterate over each object and Object.keys to catch only the keys values.
var dataset_csv = [{District: "CENTRAL", Prostitution: "44", Totalcrimecount: "18565", VehicleTheft: "552"}, {District: "WEST", Prostitution: "22", Totalcrimecount: "4324", VehicleTheft: "53"}, {District: "EAST", Prostitution: "11", Totalcrimecount: "23434" , VehicleTheft: "76"}],
datasetArr = dataset_csv.map(v => Object.keys(v).map(c => Number(v[c]) ? Number(v[c]) : v[c]));
console.log(datasetArr);

JSON understanding and arrays

I am in process of reverse engineering a JS script. Somewhere is says:
var a = [{
name: 'sample1',
data: ["Otu1", "Otu2", "Otu3", "Otu4", "Otu5"],
values: [5, 15, 250, 20, 23]
},{
name: 'sample2',
data: ["Otu1", "Otu5", "Otu6", "Otu7"],
values: [234, 29, 239, 5]
}]
First question: What type of object is it? is it JSON? Or is it an array of JSON objects?
I need to write this in this form:
var b = {
name: 'sample1',
data: ["Otu1", "Otu2", "Otu3", "Otu4", "Otu5"],
values: [5, 15, 250, 20, 23]
}
var c = {
name: 'sample2',
data: ["Otu1", "Otu5", "Otu6", "Otu7"],
values: [234, 29, 239, 5]
}
var a = b + c
Could you please help? Any insights are appreciated. Thank you community !
"First question: What type of object is it? is it JSON? Or is it an array of JSON objects?"
It's an Array of JavaScript Objects. It could be serialized into JSON data, but currently you should just see it as JavaScript code. The notation is similar, but the resulting data is different.
(And actually in your case, for the notation to be JSON-like, you'd need to use double quotes. But even then, you're still creating JavaScript Objects)
"I need to write this in this form: "
For this, you could make an Array of JavaScript Objects like this:
var a = [b, c];
You have an array of Objects here, remember JSON simply means JavaScript Object Notation

Categories