Javascript, issue in reading json with dynamic content - javascript

I have a json like this:
[
{
"Code": 100
},
{
"Drivers": [
{
"RowID": "1",
"DriverName": "ZZ",
"DriverAlias": "FF",
"DriverEmail": "YY#gmail.com",
"DriverPhone": "1121112229"
},
{
"RowID": "3",
"DriverName": "OO",
"DriverAlias": "EE",
"DriverEmail": "kkk#gmail.com",
"DriverPhone": "12121458474"
}
]
}
]
I'm reading the json in Javascript like this:
for (var i = 0; i < data.length; i++) {
Drivers[i] = {
RowID: data[1].Drivers[i].RowID,
DriverName: data[1].Drivers[i].DriverName,
DriverAlias: data[1].Drivers[i].DriverAlias,
DriverEmail: data[1].Drivers[i].DriverEmail,
DriverPhone: data[1].Drivers[i].DriverPhone
};
}
It's working but when I have my json only with one Driver like this:
[
{
"Code": 100
},
{
"Drivers": [
{
"RowID": "1",
"DriverName": "ZZ",
"DriverAlias": "FF",
"DriverEmail": "YY#gmail.com",
"DriverPhone": "1121112229"
}
]
}
]
It's not working , am I reading the json in a wrong way? Thanks.

Try this - you need to check the length of data[1].Drivers:
for (var i = 0; i < data[1].Drivers.length; i++) {
Drivers[i] = {
RowID: data[1].Drivers[i].RowID,
DriverName: data[1].Drivers[i].DriverName,
DriverAlias: data[1].Drivers[i].DriverAlias,
DriverEmail: data[1].Drivers[i].DriverEmail,
DriverPhone: data[1].Drivers[i].DriverPhone
};
}

You can shorten your code a lot, by doing this:
var Drivers = [];
for (var i = 0; i < data[1].Drivers.length; i++) {
Drivers[i] = {};
for (var j in data[1].Drivers[i]) {
Drivers[i][j] = data[1].Drivers[i][j];
}
}
That will automatically go through every object in the data[1].Drivers array, and copy over everything from those objects. This would also automatically copy over any other values that are stored in the json.

Related

How to convert Json into associative array or key value array

I have following Json which i need to insert into a table.
I want to convert each student detail into a row.
Because if i loop through the rows as per the existing structure i am reading one column as a row.
var json {
"Students":[
{
"name":{
"value":"Allan"
},
"number":{
"value":"123"
}
},
{
"name":{
"value":"Frank"
},
"number":{
"value":"456"
}
}
]
}
Ideally i want to the above as
{ "name": "Allan", "number": 123};
{ "name": "Frank", "number": 456};
I am looping through the Json as below
var objectKeys = Object.keys(json);
for (var key in objectKeys)
{
var student = json.Students;
for (var i = 0; i < student .length; i++) {
for (var column in json.Students[i]) {
window.print(column);
window.print(json.Students[i][column].value);
}
}
}
NOTE: No JQuery, want to achieve the above through normal Javascript.
If you want to transform the data, you can use Array.map
var json = {"Students":[{"name":{"value":"Allan"},"number":{"value":"123"}},{"name":{"value":"Frank"},"number":{"value":"456"}}]};
let result = json.Students.map(o => ({
name: o.name.value,
number: o.number.value
}));
console.log(result);
If you want to access the data, you can use Array.forEach
var json = {"Students":[{"name":{"value":"Allan"},"number":{"value":"123"}},{"name":{"value":"Frank"},"number":{"value":"456"}}]};
json.Students.forEach(o => console.log({name: o.name.value, number: o.number.value}));
var json = {
"Students":[
{
"name":{
"value":"Allan"
},
"number":{
"value":"123"
}
},
{
"name":{
"value":"Frank"
},
"number":{
"value":"456"
}
}
]
}
var studentData = JSON.stringify(json.Students);
var convertedData = JSON.parse(studentData.replace(/\{\"value\"\:/g,"").replace(/\}\,\"number/g,',"number').replace(/\"\}\}/g,'"}'));
Try this :)
No map or reduce. Just classic Javascript.
var json = {
"Students": [{
"name": {
"value": "Allan"
},
"number": {
"value": "123"
}
},
{
"name": {
"value": "Frank"
},
"number": {
"value": "456"
}
}
]
};
for (var student of json["Students"]) {
console.log(student); //your logic goes here.
}

how to add an element inside a json array at the specific index in a repeating block?

I am trying to add element "delete:true" after each occurrence of "_rev " mentioned in the below sample request.
Original Request:
{
"docs": [
{
"_id": "123",
"_rev": "1-7836",
},
{
"_id": "456",
"_rev": "1-1192",
}
]
}
Expected Request:
{
"docs": [
{
"_id": "123",
"_rev": "1-7836",
"_deleted" :true
},
{
"_id": "456",
"_rev": "1-1192",
"_deleted" :true
}
]
}
When I tried the below code,the ""_deleted" :true" is getting inserted after the -rev element is closed. PFB for the same and suggest.
function main(params) {
for (var i = 0; i< params.docs.length; i++) {
for (var value in params.docs[i]) {
if(value == '_rev' && params.docs[i]._rev ){
var string1 = JSON.stringify(params.docs[i]);
var str = ',';
var string2 = '"';
var string3 =str+string2+ '_deleted'+ string2+ ':' + "true" ;
var res = string1 + string3 ;
}
}
}
}
######################
[
"2018-01-23T09:44:23.568738362Z stdout:
{\"_id\":\"123\",
\"_rev\":\"1-7836\"},
\"_deleted\":true"]
Use map and Object.assign instead of generating a string
var output = params.docs.map( s => Object.assign( {}, {"_deleted" :true}, s ) );
You can then convert this to string using JSON.stringify( output );
Demo
var params = {
"docs": [{
"_id": "123",
"_rev": "1-7836",
},
{
"_id": "456",
"_rev": "1-1192",
}
]
};
var output = params.docs.map(s => Object.assign({}, {
"_deleted": true
}, s));
console.log(output);
var data = {
"docs": [
{
"_id": "123",
"_rev": "1-7836",
},
{
"_id": "456",
"_rev": "1-1192",
}
]
}
var newData = data['docs'].map(item => {
item._delete = true
return item
})
console.log(newData);
Why don't you simply put ._deleted attribute to doc, like this ?
function main(params) {
for (var i = 0; i< params.docs.length; i++) {
params.docs[i]._deleted = true;
var res = JSON.stringify(params.docs[i]);
}
}
}
Or like this :
function main(params) {
for (var i = 0; i< params.docs.length; i++) {
params.docs[i]["_deleted"] = true;
var res = JSON.stringify(params.docs[i]);
}
}
}
You can reference the not existing attribute directly and assign an value:
#!/usr/bin/js
var myJSON = { "docs": [ { "_id":"123", "_rev":"1-200" } ] }
console.log(myJSON);
myJSON.docs[0]["_deleted"]=true;
console.log(myJSON);
Output of example:
# js append.js
{ docs: [ { _id: '123', _rev: '1-200' } ] }
{ docs: [ { _id: '123', _rev: '1-200', _deleted: true } ] }
Read the more extensive example here: Add new attribute (element) to JSON object using JavaScript
So this might be a duplicate ...

Is there possible to loop inside JavaScript object literal

So this is my question (maybe stupid), is there any possible to do this:
var data {
"label" : value,
"sets" : [
for (var i=0; i < item.length; i++)
{
somedata: "data"
}
]
}
to reach result:
var data {
"label" : value,
"sets" : [
{
somedata: "data1"
},
{
somedata: "data2"
}
]
}
Much thx for help.
As jimm101 has pointed out, you are not working with JSON, that's just JavaScript (the var in there proves it) . If you want to calculate a value inside a literal JavaScript object, you can use an immediately invoked function
var data = {
"label" : value,
"sets" : (function(){
var arr = [];
for (var i=0; i < item.length; i++) {
arr.push( {somedata: "data" + i} ) ;
}
return arr;
})()
};
As dystroy has pointed out You can also use Array.map to return a transformed array, without needing an immediately invoked function, which looks a little nicer
You may use functional programming :
var data = {
"label" : "value",
"sets" : item.map(function(_,i){ return {somedata: "data"+(i+1)} })
}
Use the following:
var data = {
label: value,
get sets(){
var array = [];
/* write your logic to fill the array here. */
return array;
}
}
Reference here
As others have commented, JSON is data, not code. It looks like you're making javascript code though, since JSON also wouldn't include the var data part.
JSON => JavaScript Object Notation, a wide-spread way of representing data.
javascsript object => A structure within the javascript programming language that uses JavaScript Object Notation.
You can do something like this.
var data = {
"label" : 'my_label',
};
item = ['one','two','another'];
data.sets = [];
for (var i=0; i < item.length; i++)
{
data.sets.push({'somedata': item[i]});
}
You can use array comprehension (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Array_comprehensions), but it's not supported yet by all browsers (ECMAScript 6).
var value = "test";
var item = ["data1", "data2", "data3"];
var data = {
"label" : value,
"sets" : [for (x of item) {somedata: x}]
};
/*
Result :
data = {
"label":"test",
"sets":[
{"somedata":"data1"},
{"somedata":"data2"},
{"somedata":"data3"}
]
}
*/
You can have nested data in JSON like for example
var myObject = {
"first": "John",
"last": "Doe",
"age": 39,
"sex": "M",
"salary": 70000,
"registered": true,
"interests": [ "Reading", "Mountain Biking", "Hacking" ],
"favorites": {
"color": "Blue",
"sport": "Soccer",
"food": "Spaghetti"
},
"skills": [
{
"category": "JavaScript",
"tests": [
{ "name": "One", "score": 90 },
{ "name": "Two", "score": 96 }
]
},
{
"category": "CouchDB",
"tests": [
{ "name": "One", "score": 79 },
{ "name": "Two", "score": 84 }
]
},
{
"category": "Node.js",
"tests": [
{ "name": "One", "score": 97 },
{ "name": "Two", "score": 93 }
]
}
]
};
You can access such an array and its contents using a loop in your program
Source: http://www.json.com/

complex grouping and merging array as properties

I wish to put an array into other's array as proproties by matching their common properties. I want jobDetails's uId to match with job's uId. Possible?
var job = [{
"uId": 1
}, {
"uId": 2
}]
var jobDetails = [{
"uId": 1,
"salary": 5000
}, {
"uId": 2,
"salary": 5000
}]
is it possible to produce something like
var job = [{
"uId": 1,
"salary": [{
"uId": 1,
"salary": 5000
}]
}, {
"uId": 2,
"salary": [{
"uId": 2,
"salary": 5000
}]
}];
You may try something like this: http://jqversion.com/#!/XWFtbQb
for (var i = 0; i < job.length; i++) {
for (var j = 0; j < jobDetails.length; j++) {
if (job[i].uId == jobDetails[j].uId) {
job[i].salary = jobDetails[j];
}
}
}
console.log(job);
This is not a pure javascript solution, but I like to use underscore.js for this kind of typical actions on collections:
http://jsfiddle.net/FPwq7/
var finalCollection = [];
_.each(job, function(model){
var obj = _.findWhere(jobDetails, {uId: model.uId});
_.extend(model, {'salaray': obj});
finalCollection.push(model);
});
console.log(finalCollection);
I found that this Javascript utility belt takes care of some heavy lifting, and it makes the code a bit more pleasant to read than reading dry loops.
Yes possible , you need to play with both json objects
var array = [];
var object = {}
$.each( job, function ( k , kal ) {
$.each( jobDetails , function ( i , val) {
object.uId = i;
object.salary = val;
});
array.push(object);
});
console.log(JSON.stringify(array));

Create an object with custom structure in javascript

I need to create an array object with this exact structure:
{"item1": {
0 : {
color:"description1",
width:"description2",
height:"description3"
}
1 : {
color:"description1",
width:"description2",
height:"description3"
}
//and so on
},
"item2": {
0 : {
color:"description1",
width:"description2",
height:"description3"
}
//and so on
}
//and so on
}
Estatically works fine. Now, I want to make it dinamically. So, the main question is... How can I loop the data while constructing the object at the same time?
This is an example of the incoming object I work from:
[
{
"uid": 1,
"legendname": "item1",
"rows": [
{
"uid": 0,
"color": "482400",
"width": "482400",
"height": "25"
},
{
"uid": 1,
"color": "587898",
"width": "789658",
"height": "30"
}
]
}
{
"uid": 2,
"legendname": "item2",
"rows": [
{
"uid": 0,
"color": "482400",
"width": "482400",
"height": "25"
}
]
}
]
How can I loop the data while constructing the object at the same time?
Is not clear. But if you want to create a new structure based on the incoming one, you can use this:
// ar = your incoming object
// b_obj = your result
var b_obj = {}
for (var i = 0; i < ar.length; i++)
{
item = ar[i];
b_item = {};
for (var i_row = 0; i_row < item.rows.length; i_row++)
{
var row = {};
row.color = item.rows[i_row].color;
row.width = item.rows[i_row].width;
row.height = item.rows[i_row].height;
b_item[i_row] = row;
}
b_obj[item.legendname] = b_item;
}

Categories