Create an object with custom structure in javascript - 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;
}

Related

Postman JSON parse response body arrays inside arrays

I have this JSON Response from API call
[
{
"id": 20599,
"name": "Deliver",
"options": [
{
"id": 63775,
"name": "Item",
"dataType": "SelectMultiOption",
"required": false,
"options": [
{
"id": 426,
"name": "Towels"
},
{
"id": 427,
"name": "Toothbrush"
},
{
"id": 428,
"name": "Pillow"
}
]
}
]
}
]
I am using this code to get the id of the service "Deliver"
var data = JSON.parse(responseBody);
var loop_count = 0
for (count = 0; count < data.length; count++)
{
if (data[count].name == "Deliver")
{
var job_id = data[count].id;
postman.setEnvironmentVariable("service_id", job_id);
}
}
The questions are:
How can I get value from array "options", I need to get the "id":
63775 and store as "item_id" and the "name":"Item" as "item_name" postman variables.
Then I need to select the "options" nested in record
"Item" and select the option "name": "Toothbrush" and store in postman
variable "svc_optn_optn_name" and it's "id" stored in
"svc_optn_optn_id"
Here I am giving my own suggestion for your problem with few lines of code. I am not sure, how are you going to use these values. I also don't know if the outer options array will always have 1 item or more. I have just tried to satisfy your questions.
Please ask/comment, if you have more doubts or I am wrong.
I have created a function getAllPostmanDataFrom(obj) which takes object as parameter which is the value of data[count], gathers necessary info in other object postmanObj and returns it to the caller.
function getAllPostmanDataFrom(obj) {
const item_id = obj.options[0].id;
const item_name = obj.options[0].name;
const svc_optn_optn_name = obj.options[0].options[1].name;
const svc_optn_optn_id = obj.options[0].options[1].id;
const postmanObj = {item_id, item_name, svc_optn_optn_id, svc_optn_optn_name}; // Return object
return postmanObj;
}
var data = [
{
"id": 20599,
"name": "Deliver",
"options": [
{
"id": 63775,
"name": "Item",
"dataType": "SelectMultiOption",
"required": false,
"options": [
{
"id": 426,
"name": "Towels"
},
{
"id": 427,
"name": "Toothbrush"
},
{
"id": 428,
"name": "Pillow"
}
]
}
]
}
]
var count = 0;
var obj = data[count];
var postmanObj = getAllPostmanDataFrom(obj);
//var {item_id, item_name, svc_optn_optn_id} = postmanObj;
console. log(postmanObj)
/*
console.log(item_id);
console.log(item_name);
console.log(svc_optn_optn_id);
console.log(svc_optn_optn_name);
*/
Finally, you can use values contained in postmanObj as follows:.
postman.setEnvironmentVariable("item_id", postmanObj.item_id);
postman.setEnvironmentVariable("item_name", postmanObj.item_name);
And so on.
This is the solution
var data = JSON.parse(responseBody);
variable named as data
var loop_count = 0
for (count = 0; count < data.length; count++)
{
if (data[count].name == "Deliver")
{
var job_id = data[count].id;
postman.setEnvironmentVariable("service_id", job_id);
var job1_name = data[count].options[0].name;
postman.setEnvironmentVariable("item_name", job1_name);
var job2_id = data[count].options[0].id;
postman.setEnvironmentVariable("item_id", job2_id);
var job3_id = data[count].options[0].options[1].id;
postman.setEnvironmentVariable("svc_optn_optn_id", job3_id);
var job4_name = data[count].options[0].options[1].name;
postman.setEnvironmentVariable("svc_optn_optn_name", job4_name);
}
const data = JSON.parse(responseBody);
data.forEach(item => {
console.log(item.id); // deliver object id.
item.options.forEach(option => {
console.log(`Option Id ${option.id}`); // option id
postman.setEnvironmentVariable("service_id", option.id);
option.options(optionItem => {
if(optionItem.name == 'Toothbrush'){
postman.setEnvironmentVariable("svc_optn_optn_name", optionItem.name);
postman.setEnvironmentVariable("svc_optn_optn_id", optionItem.id);
}
});
});
});

Convert JSON from one format to other

I'm trying to convert the below JSON to another format wherein the reultant JSON dosen't contain valueChainEntity object name and also I want to delete the inputs and outputs array.Note that the structure is a parent child relation and the inputs and outputs array can be present inside the items array at any level.Even in the all levels(but only inside items array)
var inputJSON = [
{
"valueChainEntity":{
"id":308,
"valueChainEntityId":48,
"items":[
{
"valueChainEntity":{
"id":309,
"valueChainEntityId":49,
"items":[
{
"valueChainEntity":{
"id":312,
"valueChainEntityId":50,
"items":[
]
},
"inputs":[
{
"id":312,
"valueChainEntityId":50,
"items":[
]
}
],
"outputs":[
{
"id":313,
"valueChainEntityId":50
}
]
}
]
}
}
]
}
}
]
var outputJSON= [
{
"id":308,
"valueChainEntityId":48,
"items":[
{
"id":309,
"valueChainEntityId":49,
"items":[
{
"id":312,
"valueChainEntityId":50,
"items":[
]
}
]
}
]
}
]
My code:
inputJSON.forEach((item) => {
return item.valueChainEntity;
});
//which will traverse only through the first level and will not delete the **inputs** and **outputs** array..
See if following works:
function parseInputJSON(inp) {
return inp.map(function (item) {
return getValueChainEntity(item);
});
}
function getValueChainEntity(item) {
if (item['valueChainEntity'] != undefined) {
var valueChainEntity = item.valueChainEntity;
valueChainEntity.items = parseInputJSON(valueChainEntity.items);
return valueChainEntity;
}
return item;
}
var inputJSON=[
{
"valueChainEntity": {
"id": 308,
"valueChainEntityId": 48,
"items": [
{
"valueChainEntity": {
"id": 309,
"valueChainEntityId": 49,
"items": [
{
"valueChainEntity": {
"id": 312,
"valueChainEntityId": 50,
"items": []
},
"inputs": [
{
"id": 312,
"valueChainEntityId": 50,
"items": []
}
],
"outputs": [
{
"id": 313,
"valueChainEntityId": 50
}
]
}
]
}
}
]
}
}];
var newInput = parseInputJSON(inputJSON);
document.getElementById("json").innerHTML = JSON.stringify(newInput, undefined, 4);
<pre id="json"></pre>
Here's another way that is working..
Sample code
function populateChildrenRecursively(outputTypeId, valueChainEntities, parentValueChainEntity) {
for (var i = 0; i < valueChainEntities.length; i++) {
if (valueChainEntities[i].valueChainEntity.valueChainEntityId != parentValueChainEntity.valueChainEntity.valueChainEntityId && hasInput(outputTypeId, valueChainEntities[i].inputs)) {
parentValueChainEntity.valueChainEntity.items.push(valueChainEntities[i]);
if (valueChainEntities[i].outputs.length > 0) {
valueChainEntities[i].valueChainEntity.items = [];
for (var j = 0; j < valueChainEntities[i].outputs.length; j++) {
populateChildrenRecursively(valueChainEntities[i].outputs[j].outputTypeId, valueChainEntities, valueChainEntities[i]);
}
}
}
}
}
https://plnkr.co/edit/d2wtXcaU37quthBjgrCu?p=preview

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/

Javascript, issue in reading json with dynamic content

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.

converting format of JSON

I am using an AJAX query to Fuseki, that I want to visualize in a D3.js collapsable tree. However Fuseki returns the JSON in a format that the D3.js code does not recognise. like this:
{
"head": {
"vars": [ "s" ]
} ,
"results": {
"bindings": [
{
"s": {
"type": "uri",
"value": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#FourCheesesTopping"
},
"p": {
"type": "uri",
"value": "http://www.w3.org/2000/01/rdf-schema#subClassOf"
},
"o": {
"type": "uri",
"value": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#CheeseTopping"
}
]
}
}
I need to convert this JSON into this format:
{
"name": "Pizza",
"children": [
{
"name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#PizzaBase",
"children": [
]
},
{
"name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#PizzaTopping",
"children": [
{
"name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#MeatTopping",
"children": [
{
"name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#HotSpicedBeefTopping"
}
]
}
]
}
]
}
I have tried taking the JSON and putting it into a new object with the correct format, but it is not working. Here is my code:
var parent = new Object();
var childArray=[];
var child = [];
function createChildObj(_children, children, depth, id, childName, parent, x, x0, y, y0){
var childObj = new Object();
childObj._children = _children;
childObj.children = children;
childObj.depth = depth;
childObj.id =id;
childObj.name = childName;
childObj.parent= parent;
childObj.x = x;
childObj.x0 = x0;
childObj.y = y;
childObj.y0 = y0;
return childObj;
};
console.log(root.length)
for (var i=0; i<root.length; i++){
var childName = root[i]["s"]["value"];
var childObj = createChildObj("children",null, 1, 2, childName, parent, 190, 190, 180, 180);
child.push(childObj);
}
parent.name = "Pizza";
parent.depth = 0;
parent.id = 3;
parent.children= child;
parent.x0 = root.x0;
parent.x = parent.x0;
parent.y0 = root.y0;
parent.y = parent.y0;
So I am aiming to have parent as the JSON object with the data in the correct format to parse to the d3. sorry its a mess, been fiddling for ages trying to learn D3, and the learning curve is steeper than I had anticipated. Any help would be great! cheers.

Categories