I need to parse json array which consist of array inside object - javascript

Here is my JSON array which I need to parse using javascript code.
{
"individualTicketList": [{
"TicketID": 58,
"ResponderID": 1,
"Subject": "test sub",
"DueByDate": "2021-10-12"
},
{
"TicketID": 59,
"ResponderID": 1,
"Subject": "test",
"DueByDate": "2021-10-12"
}]
}
I am having an above json array and i need to display subject of each object from my json `which is inside individualticketlist here is my code.`
for(var i=0;i<jsonString.length;i++)
{
alert(a.individualTicketList[i].DueByDate);
}

Here's how to loop through it
let json = {
"individualTicketList": [{
"TicketID": 58,
"ResponderID": 1,
"Subject": "test sub",
"DueByDate": "2021-10-12"
}, {
"TicketID": 59,
"ResponderID": 1,
"Subject": "test",
"DueByDate": "2021-10-12"
}]
}
let arr = json["individualTicketList"]
for (var i = 0; i < arr.length; i++) {
console.log(arr[i].Subject);
console.log(arr[i].DueByDate);
//your other code here
}

Related

How do I create a new object from an existing object in Javascript?

Working on JavaScript app and need help in creating a new object from response received from ajax call.
The output received is array of objects, sample format below:
{
"items": [
{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to swim",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}
]
}
However, my component expects JS Object in the following format:
{
id: "e1",
title: "Express",
start: "Jan 13, 2010",
description: "Jan 13, 2010"
}
Is following approach correct, please suggest better approach if any
var content = {
"items": [{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}
}
};
var gcalEvents = {};
var jsonObj = {
"id": "e1",
"title": "Oracle Application Express",
"start": "Jan 13, 2010",
"description": "Jan 13, 2010"
};
console.log(content.items.length);
for (var index = 0; index < content.items.length; index++) {
var obj = content.items;
console.log(obj);
jsonObj.id = obj[index]["id"];
jsonObj.title = obj[index].summary;
jsonObj.start = obj[index].start.dateTime;
jsonObj.description = "";
console.log(jsonObj);
gcalEvents[index] = jsonObj;
}
console.log(gcalEvents);
You could take a more functional approach with the following:
var parsed = content.items.map(function (item) {
return {
id: item.id,
title: item.summary,
start: item.start.dateTime,
description: item.start.dateTime
}
})
This uses the map method that is attributed with arrays to loop over each item of the array and return a new array of parsed objects.
Take a look at this fuller example.
I have another way to convert this content.
Using Underscore.js to make the code more readable.
Here is the example:
var content = {
"items": [{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}, {
"id": "nj4h567r617n4vd4kq98qfjrek",
"summary": "Modern Data Architectures for Business Insights at Scale Confirmation",
"start": {
"dateTime": "2017-03-07T11:30:00+05:30"
}
}]
};
var result = _.map(content.items, function(item) {
return {
id: item.id,
title: item.summary,
start: item.start.dateTime,
description: ""
};
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
The result as following:
[
{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"title": "Learn to code",
"start": "2017-03-04T19:00:00+05:30",
"description": ""
},
{
"id": "nj4h567r617n4vd4kq98qfjrek",
"title": "Modern Data Architectures for Business Insights at Scale Confirmation",
"start": "2017-03-07T11:30:00+05:30",
"description": ""
}
]
At the core, you are trying to 'map' from one set of data to another. Javascript's mapping function of array should be sufficient. Eg.
var content = {
"items": [{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
}]
};
var results = content.items.map(function (item) {
return {
id: item.id,
title: item.summary,
start: item.start.dateTime,
description: ""
};
});
console.log(results);
var jsonObj=[];
for (var index = 0; index < content.items.length; index++) {
var obj = {};
console.log(obj);
obj["id"]=content.items[index].id;
obj["title"]=content.items[index].summary;
obj["start"]=content.items[index].start.dateTime;
obj["description"]="";
jsonObj.push(obj);
console.log(jsonObj);
//gcalEvents[index] = jsonObj;
}
This will give you jsonObj as your desired json object.
Hope this helps :)
Here's the fixed code:
One error was when you've listed the content items, a "]" was missing at the end.
The second one was that you were trying to assign a values to an undefined object, you first need to define the object eg: jsonObj = {}; and then do the assigning of values.
I've preferred to do the object define and assigning of the values in one go.
In order to have the output as an array, you just have to define the colection as an array and not am object eg: var gcalEvents = []
var content = {
"items": [
{
"id": "02egnc0eo7qk53e9nh7igq6d48",
"summary": "Learn to code",
"start": {
"dateTime": "2017-03-04T19:00:00+05:30"
}
},
{
"id": "nj4h567r617n4vd4kq98qfjrek",
"summary": "Modern Data Architectures for Business Insights at Scale Confirmation",
"start": {
"dateTime": "2017-03-07T11:30:00+05:30"
}
}
]
};
var gcalEvents = [];
var jsonObj = {
"id": "e1",
"title": "Oracle Application Express",
"start": "Jan 13, 2010",
"description": "Jan 13, 2010"
};
//console.log(content.items.length);
for(var index=0; index < content.items.length; index++){
var obj = content.items[index];
//console.log(obj);
jsonObj = {
'id': obj["id"],
'title': obj.summary,
'start': obj.start.dateTime,
'description': ""
}
//console.log(jsonObj);
gcalEvents[index] = jsonObj;
}
console.log(gcalEvents);

check array inside an array length is empty then remove the parent array from the main array

Hi How to check array inside an array length is empty then remove the parent array from the main array ,
think about i have an array
[
{
"id": 71,
"campaignAssets": [
{
"id": 128
}
]
},
{
"id": 99,
"campaignAssets": []
}
]
from above array id:71 have campaignAssets array which is length is 1 but on the other one "id": 99 dont have the campaignAssets so i have to remove the parent array which means
{
"id": 99,
"campaignAssets": []
}
so final array should be
[
{
"id": 71,
"campaignAssets": [
{
"id": 128
}
]
}
]
This proposal features two solutions,
generate a new array and assign it to the original array
delete unwanted items without generating a temporary.
1. With a new array
You could filter it with Array#filter
var data = [{ "id": 71, "campaignAssets": [{ "id": 128 }] }, { "id": 99, "campaignAssets": [] }];
data = data.filter(function (a) { return a.campaignAssets.length; });
console.log(data);
In ES6 it's even shorter
var data = [{ "id": 71, "campaignAssets": [{ "id": 128 }] }, { "id": 99, "campaignAssets": [] }];
data = data.filter(a => a.campaignAssets.length);
console.log(data);
2. Without a new array
For a in situ solution, keeping the array and delete only the elements with zero length, I suggest to use backward iteration and check the length and use Array#splice accordingly.
var data = [{ "id": 71, "campaignAssets": [{ "id": 128 }] }, { "id": 99, "campaignAssets": [] }],
i = data.length;
while (i--) {
if (!data[i].campaignAssets.length) {
data.splice(i, 1);
}
}
console.log(data);
var data =[
{
"id": 71,
"campaignAssets": [
{
"id": 128
}
]
},
{
"id": 99,
"campaignAssets": []
}
]
var i = data.length;
while (i--) {
if(data[i].hasOwnProperty('campaignAssets') && data[i]['campaignAssets'].length==0)
data.splice(i, 1)
}
// This one is wrong implementation as pointed out, it will not delete element from reducing array..
// data.forEach(function(parent,index){
// if(parent.hasOwnProperty('campaignAssets') && parent['campaignAssets'].length==0)
// data.splice(index, 1)
// });
console.log(data);

In JSON Object parent key name remove and Include its inner content

This is my JSON Object in this i want to remove "item" key from json and want to keep its inner object include with "children" and its tree like JOSN. How can I do this?
[
{
"item": {
"id": 11865,
"parentid": null,
"levelid": 63,
"name": "Total"
},
"children": [
{
"item": {
"id": 10143,
"parentid": 11865,
"levelid": 19,
"name": "Productive"
}
}
]
}
]
If I'm understanding what you want your object to look like after correctly, then this should do the trick:
var arrayOfObjects = [
{
"item": {
"id": 11865,
"parentid": null,
"levelid": 63,
"name": "Total"
},
"children": [
{
"item": {
"id": 10143,
"parentid": 11865,
"levelid": 19,
"name": "Productive"
}
}
]
}
]
arrayOfObjects.forEach(function(obj) {
obj.id = obj.item.id;
obj.parentid = obj.item.parentid;
obj.levelid = obj.item.levelid;
obj.name = obj.item.name;
delete obj.item;
});
All this is doing is manually moving the data from obj.item to obj and then deleting obj.item entirely.
I would do this:
//your original array of objects
var array = [{
"item": {
"id": 11865,
"parentid": null,
"levelid": 63,
"name": "Total"
},
"children": [
{
"item": {
"id": 10143,
"parentid": 11865,
"levelid": 19,
"name": "Productive"
}
}
]
}, ...];
array.forEach(function(parent) {
flattenKey(parent, 'item');
});
function flattenKey(parent, keyName) {
var section = parent[keyName];
var child = section ? section : {};
var keys = Object.keys(child);
keys.forEach(function(key) {
parent[key] = child[key];
})
delete parent[keyName];
}
basically, the function flattenKey would flatten any key for a given object (given its key).
logic is similar to other solutions here: iterate through child keys and assign their values to the parent object (flattening).
then it deletes the child key after step 1.
try
objArray = objArray.map( function(value){
var item = value.item;
for( var key in item )
{
value[key] = item[key];
}
delete value.item;
return value;
});
DEMO
Explanation
1) Use map to iterate on each item (value) of this given array objArray.
2) Get the item property of value, assign them to value directly
3) Finally delete the item property of the value.
Faster option
objArray = objArray.map( function(value){
var item = value.item;
var itemKeys = Object.keys(item);
for( var counter = 0; counter < itemKeys.length; counter++ )
{
value[itemKeys[counter]] = item[itemKeys[counter]];
}
delete value.item;
return value;
});
You can use a recursion, which keeps the content of item and adds the children property as well.
function delItem(a, i, aa) {
var children = a.children;
if (a.item) {
aa[i] = a.item;
aa[i].children = children;
delete a.item;
}
Array.isArray(children) && children.forEach(delItem);
}
var array = [{ "item": { "id": 11865, "parentid": null, "levelid": 63, "name": "Total" }, "children": [{ "item": { "id": 10143, "parentid": 11865, "levelid": 19, "name": "Productive" } }] }];
array.forEach(delItem);
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

Create array from complex array objects & loops in javascript

I currently have a complex orders array (coming from a JSON client) that contains multiple orders like this (contains 2):
0: {
"employee": "Nicole"
"total": 13
"lineItems": {
"elements": [2]
0: {
"name": "Burger"
"price": 8
}
1: {
"name": "Lamb"
"price": 6.50
}
}
}
1: {
"employee": "Dan"
"total": 11
"lineItems": {
"elements": [2]
0: {
"name": "Lamb"
"price": 4.50
}
1: {
"name": "Meatballs"
"price": 6.50
}
}
}
What I want to do is create a new array that loops through the above and creates new items array based on the name of the lineItems object above. i.e. final output looks something like this:
var items = {
"Burger" = {
"totalSpent" : 8
},
"Lamb" = {
"totalSpent" : 13
// Note this totalSpent is an iteration or sum of all "price" items where name/id = "Lamb"
},
"Meatballs" = {
"totalSpent" : 4.50
}
}
I'm more used to PHP and have tried a number of different versions of this but can't seem to get the desired output. Here's what I've got so far:
var orders = //As above//
// Initialising new array to hold my final values
var orderItems = [];
for (var i = 0, len = orders.length; i < len; i++){
for(var e = 0, leng = orders[i]['lineItems']['elements'].length; e < leng; e++){
var totalSpent = 0;
var id = orders[i]['lineItems']['elements'][e]['name'];
if (orders[id] in orderItems[id]){
// overwrite existing array item
orderItems[id]['totalSpent'] += orders[i]['lineItems']['elements'][e]['price'];
orderItems[id].push({totalSpent : orderItems[id]['totalSpent']});
}
else {
// Create new array item
orderItems.push(id);
orderItems[id].push({totalSpent : orders[i]['lineItems']['elements'][e]['price']});
}
}
}
Edit:
Had to correct your orders syntax, I added it to my answer so you can run the Javascript Snippet;
Changed the whole dot notation to bracket notation to make it easier to read and understand;
Corrected the bug about items remaining an empty array (it was in the inner for);
var orders = [
{
"employee": "Nicole",
"total": 13,
"lineItems": {
"elements": [
{
"name": "Burger",
"price": 8
},
{
"name": "Lamb",
"price": 6.50
}
]
}
},
{
"employee": "Dan",
"total": 11,
"lineItems": {
"elements": [
{
"name": "Lamb",
"price": 4.50
},
{
"name": "Meatballs",
"price": 6.50
}
]
}
}
];
var items = {};
// loop in orders array
for (var i = 0; i < orders.length; i++) {
var elements = orders[i]["lineItems"]["elements"];
// loop in orders[i]["lineItems"]["elements"] object
for (var eIndex in orders[i]["lineItems"]["elements"]) {
// Add new item if it doesn't already exist
if (!items.hasOwnProperty(elements[eIndex]["name"])) {
items[elements[eIndex]["name"]] = {"totalSpent": elements[eIndex]["price"]};
} else {
// If it exists, sum totalSpent
items[elements[eIndex]["name"]]["totalSpent"] += elements[eIndex]["price"];
}
}
}
console.log(items);
PS: To find out why I'm using bracket notation instead of dot notation, check this question, it's good to know!
First of all, there are some error in your order array, note the difference between {} (for objects) and []. Then it is just simple use of the map function to iterate over the arrays.
See your browser console (F12) for the result of this snippet
var orders = [{
"employee": "Nicole",
"total": 13,
"lineItems": {
"elements": [{
"name": "Burger",
"price": 8
}, {
"name": "Lamb",
"price": 6.50
}
]
}
}, {
"employee": "Dan",
"total": 11,
"lineItems": {
"elements": [{
"name": "Lamb",
"price": 6.50
}, {
"name": "Meatballs",
"price": 4.50
}]
}
}]
var items = {}
orders.map(function(order) {
order.lineItems.elements.map(function(elem) {
if (items[elem.name]) {
items[elem.name].totalSpent += elem.price
} else {
items[elem.name] = {"totalSpent": elem.price}
}
})
})
console.log(items)

reset object order javascript

I have a object like this
{
"items":{
"2":{
"id":122,
"product_id":"DE",
"price":"9.35",
},
"4":{
"id":15,
"product_id":"CH",
"price":"8.00",
}
"7":{
"id":78,
"product_id":"CH",
"price":"3.00",
}
},
"total_price":"20.35",
"item_count":2,
"unit":"CHF"
}
Do you know how i reset the items order.
now 2, 4, 7
should be 0, 1, 2
Created a JSfiddle that shows you a way.
Im using a custom format function:
function format(object) {
var items = {};
var i = 0;
for (var index in object.items) {
items[i] = object.items[index];
i++;
}
object.items = items;
}
The resulted object is this:
{
"items": {
"0": {
"id": 122,
"product_id": "DE",
"price": "9.35"
},
"1": {
"id": 15,
"product_id": "CH",
"price": "8.00"
},
"2": {
"id": 78,
"product_id": "CH",
"price": "3.00"
}
},
"total_price": "20.35",
"item_count": 2,
"unit": "CHF"
}
How about this
var obj = {
"items":{
"2":{
"id":122,
"product_id":"DE",
"price":"9.35",
},
"4":{
"id":15,
"product_id":"CH",
"price":"8.00",
},
"7":{
"id":78,
"product_id":"CH",
"price":"3.00",
}
},
"total_price":"20.35",
"item_count":2,
"unit":"CHF"
}
var keys = Object.keys(obj.items)
for (var i = 0; i < keys.length; i++) {
obj.items[i] = obj.items[keys[i]];
delete obj.items[keys[i]];
};
console.log(obj);
Object properties do not have order. I assume you want to re-name the properties, counting up from 0, but have the properties maintain the original relative ordering of their keys. (So the property with the smallest name is renamed to 0, the second-to-smallest is 1, etc.)
To do this, get all the property names, and sort the names numerically. Then, get all the values in the same over as their sorted property names. Finally, re-insert those property values with their new property names.
var itemsObj = obj["items"];
// get all names
var propertyNames = Object.keys(itemsObj);
// sort property names in numeric order: ["2", "4", "7"]
propertyNames.sort(function(a,b){ return a-b; });
// get property values, sorted by their property names
// ["2", "4", "7"] becomes [{ "id":122, .. }, { "id":15, ... }, { "id":78, ... }]
var values = propertyNames.map(function(propName) { return itemsObj[propName]; }
// clear out old property and add new property
for(var i=0; i<values.length; ++i) {
delete itemsObj[propertyNames[i]];
itemsObj[i] = values[i];
}
var data = {
"items": {
"2": {
"id": 122,
"product_id": "DE",
"price": "9.35",
},
"4": {
"id": 15,
"product_id": "CH",
"price": "8.00",
},
"7": {
"id": 78,
"product_id": "CH",
"price": "3.00",
}
},
"total_price": "20.35",
"item_count": 2,
"unit": "CHF"
};
var indices = Object.keys(data.items).map(function(i) { return parseInt(i, 10); }),
counter = 0;
indices.sort();
indices.forEach(function (i) {
if (i > counter) { // put here some more collision detecting!
data.items[counter] = data.items[i];
delete data.items[i];
counter++;
}
});
Object properties order is not guaranteed anyway. You should use an array instead.
Take a look at this answer

Categories

Resources