With some JavaScript, how can I transform a JSON from:
{
"d": {
"__count": "13",
"results": [
{
"__metadata": {
"id": "123"
},
"COAST": "East",
"STATUS": "done",
"COLOR": "blue",
}
]
}
}
TO
{
"__count": "13",
"data": [
{
"__metadata": {
"id": "123"
},
"COAST": "East",
"STATUS": "done",
"COLOR": "blue",
}
]
}
Basically removing the extra "d" parent and renaming results to data? I am using this in the context of vue-table in VueJS.
Assumed that you have the json saved in a variable 'data':
data = data.d
data.data = data.results
delete data.results
This function will do it.
function transform(json) {
var obj = JSON.parse(json);
obj.d.data = obj.d.result;
delete obj.d.result;
return JSON.stringify(obj.d);
}
One solution is to unserialize your JSON to have an object (JSON.parse()). Then to serialize only what you need (JSON.stringify()).
You can use a loop.
var res = [];
for(var k in jsonData){
res.push(jsonData[k]);
}
var jsonData = {
"d": {
"__count": "13",
"results": [
{
"__metadata": {
"id": "123"
},
"COAST": "East",
"STATUS": "done",
"COLOR": "blue",
}
]
}
};
console.log(jsonData);
var res = [];
for(var k in jsonData){
res.push(jsonData[k]);
}
console.log("result:");
console.log(res);
Related
I have an array and it looks as follow:
[
{
"DT_RowId": "row_4758",
"companies": {
"id": 23,
"email": null,
"name": "test"
},
"USERS": {
"UserId": 23
}
},.....
]
How do I slice it and get only "companies": and the result as follows:
[
{
"id": 23,
"email": null,
"name": "test"
},.....
]
to clear some issues I have added the function in which I'm using data.map
fn.loadData = function (data) {
var dataKeys = Object.keys(data);
console.log(data)// 'data' is an object
console.log(data.map(x => x.companies)) ///data.map not a function error
var infiniteList = document.getElementById('infinite-list');
infiniteList.delegate = {
createItemContent: function (i) {
return ons._util.createElement(
'<ons-list-item modifier="chevron" tappable>' + data[dataKeys[i]].name + '</ons-list-item>'
);
},
countItems: function () {
return Object.keys(data).length;
}
};
infiniteList.refresh();
}
as comments told you to do:
const data = [
{
"DT_RowId": "row_4758",
"companies": {
"id": 23,
"email": null,
"name": "test"
},
"USERS": {
"UserId": 23
}
},
{
"DT_RowId": "row_3758",
"companies": {
"id": 24,
"email": null,
"name": "test3"
},
"USERS": {
"UserId": 24
}
},]
console.log(data.map(obj=>obj.companies))
This worked:
const newArray = [];
for (let i = 0; i < companyArray.length; i++) {
newArray.push(companyArray[i].companies);
}
Thanks, everyone
I have a json file and I want to convert the data into a table with Javascript. I found some similar questions How to convert the following table to JSON with javascript? , loop through a json object, but they all use jQuery and show the table on html web. I just need a simple loop to insert row into the table. I tried 'append', 'insert' and 'insertRow', all not work. Could anyone give me a hint?
Json file:
{
"name": "lily",
"country": "china",
"age": 23
},
{
"name": "mike",
"country": "japan",
"age": 22
},
{
"name": "lucy",
"country": "korea",
"age": 25
}
My code:
var jdata = {};
jdata.cols = [
{
"id": "1",
"label": "name",
"type": "string"
},
{
"id": "2",
"label": "country",
"type":"string"
}
];
for(var i = 1; i < 3; i++){
row = [
{
"c": [
{
"v": json["hits"]["hits"][i]["_source"]["name"]
},
{
"v": json["hits"]["hits"][i]["_source"]["country"]
}
]
}
];
jdata.rows.insertRow(row);
}
Edit: Add expected output: change the json file to the following structure.
[
['lily', 'china'],
['mike', 'japan'],
['lucy', 'korea'],
]
I guess you need push (Or concat / push(...elements) if you want to add array of rows)
jdata.rows = [];
for(var i = 1; i < 3; i++){
row = [
{
"c": [
{
"v": json["hits"]["hits"][i]["_source"]["name"]
},
{
"v": json["hits"]["hits"][i]["_source"]["country"]
}
]
}
];
jdata.rows.push(row);
// for elements from row
// jdata.rows.push(...row)
}
There are a few errors in your code
The JSON needs to be an array so you can loop through each object to display.
insertRow() is a method from the Table object, jdata.rows is not a Table object but an array.
Since, you have used insertRow(), I have rewritten your code to display the table data using the Table Object methods. Here is a code snippet
Edit: You can use the push() method to create your required JSON structure. I have edited the code snippet to create your required JSON.
var jdata = {
cols: [{
"id": "1",
"label": "name",
"type": "string"
},
{
"id": "2",
"label": "country",
"type": "string"
}
],
rows: []
};
var persons = [{
"name": "lily",
"country": "china",
"age": 23
},
{
"name": "mike",
"country": "japan",
"age": 22
}, {
"name": "lucy",
"country": "korea",
"age": 25
}
];
var table = document.getElementById("table");
var header = table.createTHead();
var footer = table.createTFoot();
var rowHeader = header.insertRow(0);
jdata.cols.forEach((col, index) => {
var cell = rowHeader.insertCell(index);
cell.innerHTML = col.label;
});
persons.forEach((person, index) => {
var rowFooter = footer.insertRow(index);
rowFooter.insertCell(0).innerHTML = person.name;
rowFooter.insertCell(1).innerHTML = person.country;
jdata.rows.push([person.name, person.country]);
});
console.log(jdata.rows);
<table id="table">
</table>
I want to change my json structure, how can I do it?
im getting a json that looks like this:
body: {
"111111": {
"name": "exp1",
"status": 10000
},
"222222": {
"name": "exp2",
"status": 20000
},
"333333": {
"name": "exp3",
"status": 30000
}
}
but I need it in this structure:
body: {
bulks: [{
"id": "111111",
"name": "exp1",
"status": 100000
}, {
"id": "222222",
"name": "exp2",
"status": 200000
}, {
"id": "333333",
"name": "exp3",
"status": 300000
}]
}
Cause in my html I want to read it like this:
<div *ngIf="showingList">
<div class="list-bg" *ngFor="#bulk of listBulks | async">
ID: {{bulk.id}} name of item: {{bulk.name}}
</div>
</div>
Using Object#entries and Array#map with spread operator.
const data={body:{111111:{name:"exp1",status:1e4},222222:{name:"exp2",status:2e4},333333:{name:"exp3",status:3e4}}};
const res = {body:{bulk:Object
.entries(data.body)
.map(a=>({id: a[0], ...a[1]}))}};
console.log(res);
You can do it using reduce:
var body = {
"111111": {
"name": "exp1",
"status": 10000
},
"222222": {
"name": "exp2",
"status": 20000
},
"333333": {
"name": "exp3",
"status": 30000
}
}
var bodyArray = Object.keys(body).reduce(function(result, key) {
var item = body[key];
item.id = key;
result.push(item)
return result;
}, []);
As a simplest alternative to reduce, you could use the map() function.
const body = {
"111111": {
"name": "exp1",
"status": 10000
},
"222222": {
"name": "exp2",
"status": 20000
},
"333333": {
"name": "exp3",
"status": 30000
}
}
const newArray = Object.keys(body).map(function(key) {
const newObject = {
id: key,
...body[key]
};
return newObject;
});
console.log(newArray);
I have the following JSON:
{
"temperature": "22.2",
"power": "6",
"current": "156"
}
and I need to convert it to this explicit structure:
{
"key": "temperature",
"value": "22.2"
},
{
"key": "power",
"value": "6"
},
{
"key": "current",
"value": "156"
}
Is there an elegant, simple and quick way to do this?
Best, thx
var newStructure = Object.keys(obj).map(function(key){
return {'key':key, 'value':obj[key]}
})
Example
var obj = {
"temperature": "22.2",
"power": "6",
"current": "156"
}
var arr = Object.keys(obj).map(function(key){return {'key':key,'value':obj[key]}})
console.log(arr)
Object.hashToKeyValuePairs = function (hash) {
var ret = [];
for (var i in hash)
ret.push({ key: i, value: hash[i]});
return ret;
};
// example
document.body.innerHTML = JSON.stringify(
Object.hashToKeyValuePairs({ a: 1, b: 2, c: 3 })
);
Here is the my first JSON Array format...
[
{
"id": "1234",
"caption": "caption1"
},
{
"id": "2345",
"caption": "caption2"
},
{
"id": "3456",
"caption": "caption3"
}
]
and here is another JSON Array Format
[
[
{
"id": "1234",
"value": "value11"
},
{
"id": "2345",
"value": "value12"
},
{
"id": "3456",
"value": "value13"
}
],
[
{
"id": "1234",
"value": "value21"
},
{
"id": "2345",
"value": "value22"
},
{
"id": "3456",
"value": "value23"
}
]
]
The above mentioned Two JSON Arrays, i need to compare each one with Id and need to format a new JSON Array with caption and value using javascript.
[
[
{
"caption" : "caption1",
"value":"value11"
},
{
"caption" : "caption2",
"value":"value12"
},
{
"caption" : "caption3",
"value":"value13"
}
],
[
{
"caption" : "caption1",
"value":"value21"
},
{
"caption" : "caption2",
"value":"value22"
},
{
"caption" : "caption3",
"value":"value23"
}
]
]
Please help me out.
You can do it in many ways. Below I show two variants:
Option 1: Pure JavaScript
In this example the program preindex first array for faster access to it data, and then loops over second array with map() function to create new array of arrays:
// Create index version of first array
var aix = {};
for(var i=0;i<arr1.length;i++) {
aix[arr1[i].id] = arr1[i].caption;
}
// Loop over array of arrays
var res1 = arr2.map(function(arr22){
return arr22.map(function(a){
return {caption:aix[a.id], value:a.value};
}
});
Option 2: Using special SQL library (Alasql)
Here, you can JOIN to arrays automatically with special SQL statement:
var res2 = arr2.map(function(a){
return alasql('SELECT arr1.caption, a.[value] \
FROM ? a JOIN ? arr1 USING id',[a,arr1]);
});
You can try these variants in working snippet below or play with it in jsFiddle.
(Disclaimer: I am the author of Alasql)
var arr1 = [
{
"id": "1234",
"caption": "caption1"
},
{
"id": "2345",
"caption": "caption2"
},
{
"id": "3456",
"caption": "caption3"
}
];
var arr2 = [
[
{
"id": "1234",
"value": "value11"
},
{
"id": "2345",
"value": "value12"
},
{
"id": "3456",
"value": "value13"
}
],
[
{
"id": "1234",
"value": "value21"
},
{
"id": "2345",
"value": "value22"
},
{
"id": "3456",
"value": "value23"
}
]
];
// JavaScript version
var aix = {};
for(var i=0;i<arr1.length;i++) {
aix[arr1[i].id] = arr1[i].caption;
}
var res1 = arr2.map(function(arr22){
return arr22.map(function(a){
return {caption:aix[a.id], value:a.value};
});
});
document.getElementById("res1").textContent = JSON.stringify(res1);
// Alasql version
var res2 = arr2.map(function(a){
return alasql('SELECT arr1.caption, a.[value] FROM ? a JOIN ? arr1 USING id',[a,arr1]);
});
document.getElementById("res2").textContent = JSON.stringify(res2);
<script src="http://alasql.org/console/alasql.min.js"></script>
<p>Varian 1: JavaScript</p>
<div id="res1"></div>
<p>Variant 2: Alasql</p>
<div id="res2"></div>