How to fetch from an object that is inside arary of array - javascript

I want to access: order_items > items > order_item_name
{
"order_id": 14858,
"parent_id": 0,
"date_created": "2020-05-17 07:31:42",
"date_created_gmt": "2020-05-17 07:31:42",
"status": "wc-completed",
"customer_id": 9,
"customer": {
"customer_id": 9,
"user_id": 3,
"username": "husam",
"first_name": "Hosam",
"last_name": "amazon",
"email": "ecommerce#amazonfoods.ae",
},
"order_items": [
{
"order_item_id": 152,
"order_id": 14858,
"product_id": 9095,
"shipping_tax_amount": 0,
"item": {
"order_item_id": 152,
"order_item_name": "Amazon Cheddar Cheese, 50g",
"order_item_type": "line_item",
"order_id": 14858
}
},
{
"order_item_id": 153,
"order_id": 14858,
"product_id": 9063,
"shipping_tax_amount": 0,
"item": {
"order_item_id": 153,
"order_item_name": "Amazon 1121 Golden Sella Rice, 5kg",
"order_item_type": "line_item",
"order_id": 14858
}
},
]
},
Since it is in the loop and can be seen here:
const ordersTest = [];
for (let i = 0; i < props.allOrdersState.length &&
props.allOrdersState.length; i++) {
ordersTest.push({
state:props.allOrdersState.length ? props.allOrdersState[i]['customer']['state'] :'',
first_name:props.allOrdersState.length ? props.allOrdersState[i]['customer']['first_name'] :'',
orderItems: [{
itemName:props.allOrdersState.length ? props.allOrdersState[i]['order_items'][i]['item']['order_item_name'] :'',
}],
});
}
I want to access the order_item_name but it gives an error of undefined. however, the first name and other details can be accessed.

It looks like each order has multiple orderItems, so I assume you are trying to map them? The length conditionals weren't needed since the for loop would not have run if length equaled 0. Also, there is no "state" property so I changed it to "status".
for (let i = 0; i < props.allOrdersState.length; i++) {
ordersTest.push({
status: props.allOrdersState[i]['status'],
first_name: props.allOrdersState[i]['customer']['first_name'],
orderItems: props.allOrdersState[i].order_items.map((oi) => ({
itemName: oi['item']['order_item_name']
}))
})
}
const props = {
allOrdersState: [
{
"order_id": 14858,
"parent_id": 0,
"date_created": "2020-05-17 07:31:42",
"date_created_gmt": "2020-05-17 07:31:42",
"status": "wc-completed",
"customer_id": 9,
"customer": {
"customer_id": 9,
"user_id": 3,
"username": "husam",
"first_name": "Hosam",
"last_name": "amazon",
"email": "ecommerce#amazonfoods.ae",
},
"order_items": [
{
"order_item_id": 152,
"order_id": 14858,
"product_id": 9095,
"shipping_tax_amount": 0,
"item": {
"order_item_id": 152,
"order_item_name": "Amazon Cheddar Cheese, 50g",
"order_item_type": "line_item",
"order_id": 14858
}
},
{
"order_item_id": 153,
"order_id": 14858,
"product_id": 9063,
"shipping_tax_amount": 0,
"item": {
"order_item_id": 153,
"order_item_name": "Amazon 1121 Golden Sella Rice, 5kg",
"order_item_type": "line_item",
"order_id": 14858
}
},
]
}
]
}
const ordersTest = [];
for (let i = 0; i < props.allOrdersState.length; i++) {
ordersTest.push({
status: props.allOrdersState[i]['status'],
first_name: props.allOrdersState[i]['customer']['first_name'],
orderItems: props.allOrdersState[i].order_items.map((oi) => ({
itemName: oi['item']['order_item_name']
}))
})
}
console.log(ordersTest)

You can use the recursive method to find the fields you want.
let answer = [];
function indexOf(obj, to) {
if (obj.hasOwnProperty(to)) {
answer.push(obj[to]);
} else if(Object.prototype.toString.call(obj) === '[object Object]') {
Object.values(obj).filter(item => typeof (item) === 'object').map(item => {
let newObj = item;
indexOf(newObj, to);
})
} else if(Object.prototype.toString.call(obj) === '[object Array]') {
obj.map(item=>{
let newObj = item;
indexOf(newObj, to);
})
}
return answer;
}
My method is a little lax, but it's OK to meet your requirements.
const obj = {
"order_id": 14858,
"parent_id": 0,
"date_created": "2020-05-17 07:31:42",
"date_created_gmt": "2020-05-17 07:31:42",
"status": "wc-completed",
"customer_id": 9,
"customer": {
"customer_id": 9,
"user_id": 3,
"username": "husam",
"first_name": "Hosam",
"last_name": "amazon",
"email": "ecommerce#amazonfoods.ae",
},
"order_items": [
{
"order_item_id": 152,
"order_id": 14858,
"product_id": 9095,
"shipping_tax_amount": 0,
"item": {
"order_item_id": 152,
"order_item_name": "Amazon Cheddar Cheese, 50g",
"order_item_type": "line_item",
"order_id": 14858
}
},
{
"order_item_id": 153,
"order_id": 14858,
"product_id": 9063,
"shipping_tax_amount": 0,
"item": {
"order_item_id": 153,
"order_item_name": "Amazon 1121 Golden Sella Rice, 5kg",
"order_item_type": "line_item",
"order_id": 14858
}
},
]
};
let answer = [];
function indexOf(obj, to) {
if (obj.hasOwnProperty(to)) {
answer.push(obj[to]);
} else if(Object.prototype.toString.call(obj) === '[object Object]') {
Object.values(obj).filter(item => typeof (item) === 'object').map(item => {
let newObj = item;
indexOf(newObj, to);
})
} else if(Object.prototype.toString.call(obj) === '[object Array]') {
obj.map(item=>{
let newObj = item;
indexOf(newObj, to);
})
}
return answer;
}
console.log(indexOf(obj, 'order_item_name'));

I just solved the issue. I pushed the orderItems along with firstName and other details to the empty array(ordersTest = [];) and all the items moved to the array and then I accessed each item details and order details from the array.
for (let i = 0; i < props.allOrdersState.length &&
props.allOrdersState.length; i++) {
ordersTest.push({
state:props.allOrdersState.length ? props.allOrdersState[i]['customer']['state'] :'',
first_name:props.allOrdersState.length ? props.allOrdersState[i]['customer']['first_name'] :'',
orderItems: [{
itemName:props.allOrdersState.length ? props.allOrdersState[i]['order_items']:'',
}],
});
}````
Then I accessed each element like:
{row.itemName.map((historyRow) => (
<div style={{border:'1px solid #041e41',padding:'10px'}}>
<Typography>{historyRow.item.order_item_name}</Typography>
<Typography gutterBottom component="div">
<strong> Shipment Amount:</strong> {historyRow.shipping_amount}
</Typography>
<Typography>
<strong> product Quantity:</strong> {historyRow.product_qty}
</Typography>
<Typography>
<strong>Tax Amount:</strong> {historyRow.tax_amount}
</Typography>
</div>
))}
I have mapped over row because I am mapping rows of the table and inside each row i have take collapsed of material UI, so each row contains single record:
<TableBody>
{ordersTest.map((row) => (
<Row key={row.order_id} row={row} />
))}
</TableBody>
And in each single record I am fetching detials and there is again loop over items.

Related

Core Javascript Question -- Delete Object in a json file sourced from a column if conditions meet

the reason I need the code to work in core javascript is the tool we use, it uses Rhino from mozilla, so it cannot contain objects or methods related to manipulation of web pages.
I am trying to compare data from two json files using core javascript, When the order_number and extid is same we compare the count(fullfilments.line_items) and quantity(which is the sum of all the quantities of all line items under that fulfillment, fullfilments.line_items.quantity) . If the order_number and ext_id combination match along with count and sum above, do nothing. If no match, we remove the refund. the code works fine in Visual Studio. I am new to pentaho and I think the code needs to be changed as only core js works with this tool.
In the Orders file are sample json structure, for example Order_number (66 in this case) need to calculate and compare the count of line items(6 in this case) along with the Quantity of items(7 in this case), if it doesn't match need to remove Object Refund along with its elements, else No Changes.
``````Sample File````````
[
{
"app_id": 111,
"fulfillments":
[
{
"id": 39828,
"order_id": 450625,
"receipt": {},
"service": "manual",
"shipment_status": null,
"status": "success",
"updated_at": "2022-05-24",
"line_items":
[{
"id": 376,
"quantity": 2
},
{
"id": 992,
"quantity": 1
},
{
"id": 929,
"quantity": 1
},
{
"id": 768,
"quantity": 1
},
{
"id": 929,
"quantity": 1
},
{
"id": 768,
"quantity": 1
}
]
}
],
"line_items": [],
"name": "#59",
"number": 6,
"order_number": 66,
"ext_id": 110,
"refunds": [
{
"id": 80,
"created_at": "2000-06-17T14:31:06-04:00"
}
]
},
{
"app_id": 111,
"fulfillments": [
{
"id": 398000,
"order_id": 450005,
"receipt": {},
"service": "manual",
"shipment_status": null,
"status": "success",
"updated_at": "2022-05-24",
"line_items":
[{
"id": 376,
"quantity": 2
},
{
"id": 992,
"quantity": 1
},
{
"id": 929,
"quantity": 1
},
{
"id": 768,
"quantity": 1
}
]
}
],
"line_items": [],
"name": "#59",
"number": 6,
"order_number": 67,
"ext_id": 114,
"refunds": [
{
"id": 81,
"created_at": "2000-06-17T14:31:06-04:00"
}
]
},
{
"app_id": 111,
"fulfillments": [
{
"id": 39828,
"order_id": 450625,
"receipt": {},
"service": "manual",
"shipment_status": null,
"status": "success",
"updated_at": "2022-05-24",
"line_items":
[{
"id": 376,
"quantity": 2
},
{
"id": 768,
"quantity": 1
},
{
"id": 929,
"quantity": 2
},
{
"id": 768,
"quantity": 2
}
]
}
],
"line_items": [],
"name": "#59",
"number": 6,
"order_number": 68,
"ext_id": 113,
"refunds": [
{
"id": 80,
"created_at": "2000-06-17T14:31:06-04:00"
}
]
}
]
```````````````````````````````json`````````````
//resultset file content
[
{
"order_number": 66,
"extid":110,
"line_items_count": 6,
"quantity": 7
},
{
"order_number": 67,
"extid":114,
"line_items_count": 4,
"quantity": 7
},
{
"order_number": 68,
"extid":113,
"line_items_count": 4,
"quantity": 6
}
]
`````````````````````````````````````````````````Code`````````````````
/**
* orders.json file has some sample orders
* resultset.json file has results from sql Lookup to the orders.
*
*/
const orders = require('./orders.json');
function compare(order) {
let isMatched = false;
let resultSet = require('./resultset.json');
let result = resultSet.find(function (item) {
return item.order_number === order.order_number;
});
if (
result &&
result.line_items_count === order.items &&
result.quantity === order.quantity
) {
isMatched = true;
}
return isMatched;
}
function fixOrders(orders) {
orders.map(function (order) {
let { order_number, line_items } = order;
let quantity = line_items.reduce(function (quantity, line_item) {
return (quantity += line_item.quantity);
}, 0);
if (!compare({ order_number, items: line_items.length, quantity })) {
delete order.refunds;
}
});
return orders;
}
let fixedOrders = fixOrders(orders);
console.log(fixedOrders);
// store in output.js
//========================================
// var fs = require('fs');
// fs.writeFile('outputFile.json', JSON.stringify(fixedOrders), (err) => {
// if (err) console.log(err);
// else {
// console.log('File written successfully\n');
// // console.log('The written has the following contents:');
// // console.log(fs.readFileSync('outputFile.json', 'utf8'));
// }
// });
[PDI Flow][1]
[1]: https://i.stack.imgur.com/3OzQE.png

Get object value based on conditions within nested array objects

I have an array of objects called orders:
const orders = [
{
"order_id": 47445,
"order_type": "Wholesale",
"items": [
{
"id": 9,
"department": "Womens",
"type": "Dress",
"quantity": 4,
"detail": {
"ID": 13363,
"On Sale": 1,
}
}
]
}
];
I need to get the quantity when both the order_type (Wholesale) and items.detail.ID (13363) match.
I have so far tried the following:
const result = orders.find(item => item.order_type == "Wholesale").items
.reduce((total, item) => {
if(item.detail.ID == 13363) {
return item.quantity;
}
}, 0);
Where result correctly returns 4
My issue, and I'm sure I am missing something very simple is that when I have multiple items in my orders array, it fails.
const orders = [
{
"order_id": 47445,
"order_type": "Wholesale",
"items": [
{
"id": 9,
"department": "Womens",
"type": "Dress",
"quantity": 4,
"detail": {
"ID": 13363,
"On Sale": 1,
}
},
{
"id": 56,
"department": "Womens",
"type": "Skirt",
"quantity": 12,
"detail": {
"ID": 76884,
"On Sale": 0,
}
},
{
"id": 89,
"department": "Mens",
"type": "Shirts",
"quantity": 20,
"detail": {
"ID": 98223,
"On Sale": 1,
}
}
]
}
];
The same
const result = orders.find(item => item.order_type == "Wholesale").items
.reduce((total, item) => {
if(item.detail.ID == 13363) {
return item.quantity;
}
}, 0);
returns undefined
Thank you
The find helper just returns the first match, so you need to use another helper like filter, like this:
const ID = 13363;
const result = orders
.filter((order) => order.order_type === 'Wholesale')
.reduce((acc, curr) => {
const items = curr.items.filter((item) => item.detail.ID === ID);
console.log(items);
// You can sum the matching items and then push them into the acc array
const quantity = items.reduce((sum, item) => (sum += item.quantity), 0);
acc.push(quantity);
return acc;
}, []);
This will return an array of matching quantities.
Not sure about the use case but here you go
const result = orders.find(item => item.order_type == "Wholesale").items
.reduce((total, item) => {
if (item.detail.ID == 13363) {
total += item.quantity;
}
return total
}, 0);
You can even create a function to make the search dynamic.
const orders = [
{
"order_id": 47445,
"order_type": "Wholesale",
"items": [
{
"id": 9,
"department": "Womens",
"type": "Dress",
"quantity": 4,
"detail": {
"ID": 13363,
"On Sale": 1,
}
},
{
"id": 56,
"department": "Womens",
"type": "Skirt",
"quantity": 12,
"detail": {
"ID": 76884,
"On Sale": 0,
}
},
{
"id": 89,
"department": "Mens",
"type": "Shirts",
"quantity": 20,
"detail": {
"ID": 98223,
"On Sale": 1,
}
}
]
}
];
findMyItem=( ID )=>{
var result = null ;
const result2 = orders.find(item => item.order_type == "Wholesale").items
.map(( item) => {
if(item.detail.ID == ID ) {
result = item.quantity;
}
}, 0);
return result ;
}
console.log( "result" ,findMyItem( 13363 ) )
console.log( "result" ,findMyItem( 98223) )
console.log( "result" ,findMyItem( 76884) )
You could use Array.find() on the orders array to find the correct order, searching for the first order that matches both the order_type and has an item matching the desired itemId (using Array.some()).
If this order exists, we can then find the corresponding item quantity using .find() again,
const orders = [ { "order_id": 47445, "order_type": "Wholesale", "items": [ { "id": 9, "department": "Womens", "type": "Dress", "quantity": 4, "detail": { "ID": 13363, "On Sale": 1, } }, { "id": 56, "department": "Womens", "type": "Skirt", "quantity": 12, "detail": { "ID": 76884, "On Sale": 0, } }, { "id": 89, "department": "Mens", "type": "Shirts", "quantity": 20, "detail": { "ID": 98223, "On Sale": 1, } } ] } ]
function findItemQuantity(orders, orderType, itemId) {
// Find the first order with the right order_type and containing the right item id
const order = orders.find(order => order.order_type = orderType && order.items.some(item => item.detail.ID === itemId));
if (!order) {
return null;
}
const item = order.items.find(item => item.detail.ID === itemId);
if (!item) {
return null;
}
return item.quantity;
}
console.log("Quantity found:", findItemQuantity(orders, 'Wholesale', 13363))
console.log("Quantity found:", findItemQuantity(orders, 'Wholesale', 76884))
const result = orders
.filter(order => order.order_type == "Wholesale")
.map(order => order.items.find(item => item.detail.ID == 13363))
.filter(item => item)
.reduce((total, { quantity }) => quantity + total, 0);
const orders = [{
"order_id": 47445,
"order_type": "Wholesale",
"items": [{
"id": 9,
"department": "Womens",
"type": "Dress",
"quantity": 4,
"detail": {
"ID": 13363,
"On Sale": 1,
}
}]
},
{
"order_id": 47445,
"order_type": "Whole",
"items": [{
"id": 9,
"department": "Womens",
"type": "Dress",
"quantity": 4,
"detail": {
"ID": 13363,
"On Sale": 1,
}
}]
}
]
const result = orders.reduce(v => {
return v.items.map(a => {
if (v.order_type == 'Wholesale' && a.detail.ID == 13363) {
return v
}
})
})
console.log(result)
const orders = [{
"order_id": 47445,
"order_type": "Wholesale",
"items": [{
"id": 9,
"department": "Womens",
"type": "Dress",
"quantity": 4,
"detail": {
"ID": 13363,
"On Sale": 1,
}
}]
}];
var result = null;
const result2 = orders.find(item => item.order_type == "Wholesale").items
.map((item) => {
if (item.detail.ID == 98223) {
result = item.quantity;
}
}, 0);
console.log("result", result)

JavaScript sort array of object based on the value (conditional sorting)

I've an array like this:
[{"category_id":101,"category_name":"abc","state":null},
{"category_id":204,"category_name":"test","state":null},
{"category_id":7,"category_name":"pqr","state":"1526985908122"},
{"category_id":103,"category_name":"User","state":null},
{"category_id":2,"category_name":"System","state":null},
{"category_id":205,"category_name":"xyz","state":"1526985908019"},
{"category_id":203,"category_name":"dash","state":null},
{"category_id":4,"category_name":"hello","state":null},
{"category_id":206,"category_name":"demo","state":"1526985908187"},
{"category_id":6,"category_name":"about","state":null},
{"category_id":3,"category_name":"role","state":null}]
I want to sort this array based on the value of state property like you can see state has null and some numeric value here.
If state != null then sort in ascending order and
if state == null then sort in descending order (based on category id)
So the actual result should be like this:
[{"category_id":205,"category_name":"xyz","state":"1526985908019"},
{"category_id":7,"category_name":"pqr","state":"1526985908122"},
{"category_id":206,"category_name":"demo","state":"1526985908187"},
{"category_id":204,"category_name":"test","state":null},
{"category_id":203,"category_name":"dash","state":null},
{"category_id":103,"category_name":"User","state":null},
{"category_id":101,"category_name":"abc","state":null},
{"category_id":6,"category_name":"about","state":null},
{"category_id":4,"category_name":"hello","state":null},
{"category_id":3,"category_name":"role","state":null},
{"category_id":2,"category_name":"System","state":null}]
So it should sort first 3 records based on state value in ascending order and other records based on null value in descending order based on category id.
This is what I've tried referencing this article:
https://technology.amis.nl/2007/08/24/how-to-fix-your-number-sorting-problems-in-javascript/
var ALMOST_ZERO = -0.00000001;
records.sort(function(a,b){
console.log(`comparing ${a.state},${b.state}`);
var left = a.state != null ? a.state : ALMOST_ZERO;
var right = b.state != null ? b.state : ALMOST_ZERO;
return right-left;
});
Any help would be appreciated.
Thanks
Here's a concise version. By using ||, whenever the upper expression(s) evaluate to 0, it moves on to test the next lower expression:
const arr=[{"category_id":101,"category_name":"abc","state":null},{"category_id":204,"category_name":"test","state":null},{"category_id":7,"category_name":"pqr","state":"1526985908122"},{"category_id":103,"category_name":"User","state":null},{"category_id":2,"category_name":"System",state:null},{"category_id":205,"category_name":"xyz","state":"1526985908019"},{"category_id":203,"category_name":"dash","state":null},{"category_id":4,"category_name":"hello","state":null},{"category_id":206,"category_name":"demo","state":"1526985908187"},{"category_id":6,"category_name":"about","state":null},{"category_id":3,"category_name":"role","state":null}]
arr.sort((a, b) => (
(a.state === null) - (b.state === null)
|| a.state - b.state
|| b.category_id - a.category_id
));
console.log(arr);
Console version:
ES5 version:
var arr = [{ "category_id": 101, "category_name": "abc", "state": null }, { "category_id": 204, "category_name": "test", "state": null }, { "category_id": 7, "category_name": "pqr", "state": "1526985908122" }, { "category_id": 103, "category_name": "User", "state": null }, { "category_id": 2, "category_name": "System", state: null }, { "category_id": 205, "category_name": "xyz", "state": "1526985908019" }, { "category_id": 203, "category_name": "dash", "state": null }, { "category_id": 4, "category_name": "hello", "state": null }, { "category_id": 206, "category_name": "demo", "state": "1526985908187" }, { "category_id": 6, "category_name": "about", "state": null }, { "category_id": 3, "category_name": "role", "state": null }];
arr.sort(function (a, b) {
return (a.state === null) - (b.state === null) || a.state - b.state || b.category_id - a.category_id;
});
console.log(arr);
#sky, try below solution
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
var test= [{"category_id":101,"category_name":"abc","state":null},
{"category_id":204,"category_name":"test","state":null},
{"category_id":7,"category_name":"pqr","state":"1526985908122"},
{"category_id":103,"category_name":"User","state":null},
{"category_id":2,"category_name":"System","state":null},
{"category_id":205,"category_name":"xyz","state":"1526985908019"},
{"category_id":203,"category_name":"dash","state":null},
{"category_id":4,"category_name":"hello","state":null},
{"category_id":206,"category_name":"demo","state":"1526985908187"},
{"category_id":6,"category_name":"about","state":null},
{"category_id":3,"category_name":"role","state":null}];
function sortByKeyAsc(array, key) {
return array.sort(function (a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
function sortByKeyDesc(array, key) {
return array.sort(function (a, b) {
var x = a[key]; var y = b[key];
return ((x > y) ? -1 : ((x < y) ? 1 : 0));
});
}
console.log(sortByKeyDesc(test,"state") );
</script>
</head>
<body>
</body>
</html>
Try following
var arr = [{"category_id":101,"category_name":"abc","state":null},{"category_id":204,"category_name":"test","state":null},{"category_id":7,"category_name":"pqr","state":"1526985908122"},{"category_id":103,"category_name":"User","state":null},{"category_id":2,"category_name":"System",state:null},{"category_id":205,"category_name":"xyz","state":"1526985908019"},{"category_id":203,"category_name":"dash","state":null},{"category_id":4,"category_name":"hello","state":null},{"category_id":206,"category_name":"demo","state":"1526985908187"},{"category_id":6,"category_name":"about","state":null},{"category_id":3,"category_name":"role","state":null}];
arr.sort((a,b) => {
// If both null, sort by category_id descending
if(!a.state && !b.state) return b.category_id - a.category_id;
// if first value is null, swap
else if(!a.state) return 1;
// if second value is null, no change
else if (!b.state) return -1;
// if both have values sort by state ascending.
else return a.state - b.state;
})
console.log(arr);
var data = [{
"category_id": 101,
"category_name": "abc",
"state": null
},
{
"category_id": 204,
"category_name": "test",
"state": null
},
{
"category_id": 7,
"category_name": "pqr",
"state": "1526985908122"
},
{
"category_id": 103,
"category_name": "User",
"state": null
},
{
"category_id": 2,
"category_name": "System",
"state": null
},
{
"category_id": 205,
"category_name": "xyz",
"state": "1526985908019"
},
{
"category_id": 203,
"category_name": "dash",
"state": null
},
{
"category_id": 4,
"category_name": "hello",
"state": null
},
{
"category_id": 206,
"category_name": "demo",
"state": "1526985908187"
},
{
"category_id": 6,
"category_name": "about",
"state": null
},
{
"category_id": 3,
"category_name": "role",
"state": null
}
];
var valueWithoutNull = data.filter(val => val.state != null);
var valueWithNull = data.filter(val => val.state == null);
valueWithoutNull = valueWithoutNull.sort((a, b) => a.state - b.state);
var result = [...valueWithoutNull, ...valueWithNull];
console.log(result);
var data = [{
"category_id": 101,
"category_name": "abc",
"state": null
},
{
"category_id": 204,
"category_name": "test",
"state": null
},
{
"category_id": 7,
"category_name": "pqr",
"state": "1526985908122"
},
{
"category_id": 103,
"category_name": "User",
"state": null
},
{
"category_id": 2,
"category_name": "System",
"state": null
},
{
"category_id": 205,
"category_name": "xyz",
"state": "1526985908019"
},
{
"category_id": 203,
"category_name": "dash",
"state": null
},
{
"category_id": 4,
"category_name": "hello",
"state": null
},
{
"category_id": 206,
"category_name": "demo",
"state": "1526985908187"
},
{
"category_id": 6,
"category_name": "about",
"state": null
},
{
"category_id": 3,
"category_name": "role",
"state": null
}
];
data = data.sort(function(a, b) {
if (a.state == null)
return 1;
if (b.state == null)
return -1;
return a.state - b.state;
});
console.log(data);

Iteration over javascript objects

Write a function that takes Season number and episode number as input
and gives all the information about that particular episode as output
After taking inputs from the user as season number and episode number, it doesn't give output as the information about that particular episode
let BigBang = {
"_embedded": {
"episodes": [
{
"id": 2913,
"name": "Pilot",
"season": 1,
"number": 1,
"airdate": "2007-09-24",
"airtime": "20:30",
"airstamp": "2007-09-25T00:30:00+00:00",
"runtime": 30,
"_links": {
"self": {
"href": "http:\/\/api.tvmaze.com\/episodes\/2913"
}
}
},
{
"id": 2914,
"name": "The Big Bran Hypothesis",
"season": 1,
"number": 2,
"airdate": "2007-10-01",
"airtime": "20:30",
"airstamp": "2007-10-02T00:30:00+00:00",
"runtime": 30,
"image": {
"medium": "http:\/\/static.tvmaze.com\/uploads\/images\/medium_landscape\/4\/12369.jpg",
"original": "http:\/\/static.tvmaze.com\/uploads\/images\/original_untouched\/4\/12369.jpg"
},
}
let season = prompt('Enter Season number');
let number = prompt('Enter Episode number');
let AllInfo = (season,number) => {
for(let current in BigBang._embedded.episodes) {
if(BigBang._embedded.episodes[current].season === season) {
if(BigBang._embedded.episodes[current].number === number) {
let Detail = BigBang._embedded.episodes[current];
alert(Detail);
}
}
}
AllInfo(season,number);
}
Try using .find instead, it'll make the code a lot cleaner:
let BigBang = {
"_embedded": {
"episodes": [{
"id": 2913,
"name": "Pilot",
"season": 1,
"number": 1,
"airdate": "2007-09-24",
"airtime": "20:30",
"airstamp": "2007-09-25T00:30:00+00:00",
"runtime": 30,
"_links": {
"self": {
"href": "http:\/\/api.tvmaze.com\/episodes\/2913"
}
}
},
{
"id": 2914,
"name": "The Big Bran Hypothesis",
"season": 1,
"number": 2,
"airdate": "2007-10-01",
"airtime": "20:30",
"airstamp": "2007-10-02T00:30:00+00:00",
"runtime": 30,
"image": {
"medium": "http:\/\/static.tvmaze.com\/uploads\/images\/medium_landscape\/4\/12369.jpg",
"original": "http:\/\/static.tvmaze.com\/uploads\/images\/original_untouched\/4\/12369.jpg"
},
}
]
}
}
//const inputSeason = prompt('Enter Season number');
const inputSeason = 1;
//const inputNumber = prompt('Enter Episode number');
const inputNumber = 2;
const foundEpisode = BigBang._embedded.episodes.find(({ season, number}) => {
return season === inputSeason && number === inputNumber;
});
if (foundEpisode) console.log(foundEpisode);
else console.log('No matching season/number found!');
You could do that easier with the find() method on your array.
let episode = BigBang._embedded.episodes.find((e) => {
return e.season === season && e.number === number;
});
if (episode) {
alert(episode.name);
}
I have debugged your code and saw that you call AllInfo function within AllInfo .So there is recursive call happen in your code. So remove calling of AllInfo from AllInfo function, your issue will be fixed. Try the following code.
let BigBang = {
"_embedded": {
"episodes": [
{
"id": 2913,
"name": "Pilot",
"season": 1,
"number": 1,
"airdate": "2007-09-24",
"airtime": "20:30",
"airstamp": "2007-09-25T00:30:00+00:00",
"runtime": 30,
"_links": {
"self": {
"href": "http:\/\/api.tvmaze.com\/episodes\/2913"
}
}
},
{
"id": 2914,
"name": "The Big Bran Hypothesis",
"season": 1,
"number": 2,
"airdate": "2007-10-01",
"airtime": "20:30",
"airstamp": "2007-10-02T00:30:00+00:00",
"runtime": 30,
"image": {
"medium": "http:\/\/static.tvmaze.com\/uploads\/images\/medium_landscape\/4\/12369.jpg",
"original": "http:\/\/static.tvmaze.com\/uploads\/images\/original_untouched\/4\/12369.jpg"
},
}]}};
let season = 1;
let number = 2;
let AllInfo = (season,number) => {
for(let current in BigBang._embedded.episodes) {
if(BigBang._embedded.episodes[current].season === season) {
if(BigBang._embedded.episodes[current].number === number) {
let Detail = BigBang._embedded.episodes[current];
alert(JSON.stringify(Detail,null,4));
}
}
}
}
AllInfo(season,number);

Converting javascript object to ordered comma separated value

I am trying to get the items in the json arranged in an orderly manner. I was able to select the "term" values present in the json, but is it possible to arrange this in the manner I have shown in the expected output part? I have added a jsfiddle link to show where I have reached:
[
{
"Link": "http://testLink.com/1",
"_index": "test",
"_source": {
"Author": "SAM",
"Map": [
{
"Company": [
{
"Apple_Inc": [
{
"count": 1,
"term": "Apple"
}
],
"sector": "Technology",
"term": "Apple Inc",
"ticker": "AAPL",
"type": "BCap"
}
],
"count": 1,
"term": "Company"
},
{
"Country": [
{
"Canada": [
{
"Canada": [
{
"count": 1,
"term": "Toronto"
}
],
"count": 1,
"term": "Canada"
}
],
"United_States": [
{
"count": 1,
"term": "United States"
}
],
"currency": "Dollar (USD)",
"index": "DOW JONES INDUS. AVG , S&P 500 INDEX , NASDAQ COMPOSITE INDEX",
"region": "North Americas",
"term": "Canada"
}
],
"count": 1,
"term": "Country"
},
{
"Personality": [
{
"count": 1,
"term": "Bart Prince"
},
{
"count": 1,
"term": "Thomas"
},
{
"count": 1,
"term": "Deborah Hornstra"
},
{
"count": 1,
"term": "Henderson Sotheby"
},
{
"count": 1,
"term": "Max Alliance"
}
],
"count": 5,
"term": "Personality"
}
]
},
"id": "YMFT112"
},
{
"Link": "http://testLink.com/2",
"_id": "YMFT113",
"_index": "test",
"_source": {
"Author": "MAX",
"Map": [
{
"Company": [
{
"Microsoft Corp": [
{
"count": 1,
"term": "Microsoft"
}
],
"sector": "Technology",
"term": "Microsoft",
"ticker": "AAPL",
"type": "BCap"
}
],
"count": 1,
"term": "Company"
},
{
"Country": [
{
"Brazil": [
{
"count": 1,
"term": "Brazil"
}
],
"currency": "Dollar (USD)",
"region": "South Americas",
"term": "Brazil"
}
],
"count": 1,
"term": "Country"
},
{
"SalesRelated": [
{
"count": 1,
"term": "traffic"
}
]
},
{
"Personality": [
{
"count": 1,
"term": "Maximor"
},
{
"count": 1,
"term": "R.V.P"
},
{
"count": 1,
"term": "Wenger"
},
{
"count": 1,
"term": "SAF"
}
],
"count": 4,
"term": "Personality"
}
]
}
}
]
http://jsbin.com/exuwet/3/edit
Prompt Input
If field Selected = Country,
Expected Output:
YMFT112; Country; United States; United States; NA; http://testLink.com/1;
YMFT112; Country; Canada; Canada; Toronto; http://testLink.com/1;
YMFT113; Country; Brazil; Brazil; NA; http://testLink.com/2;
If field Selected = Company,
Expected Output:
YMFT112; Company; Apple Inc; Apple; http://testLink.com/1;
YMFT113; Company; Microsoft Corp; Microsoft; http://testLink.com/2;
You can use the JSON object when natively available or use JSON2 as a shim.
After that it's just a matter of using JavaScript's built in sorting capability. You supply a function that compares to array items against each other
var myArray = JSON.parse(jsonString);
myArray.sort(function(a, b){
var nameA = a._source.Map.Company.term;
var nameB = b._source.Map.Company.term;
if (nameA === nameB) {
return 0;
} else if (nameA < nameB) {
return -1
}
return 1;
});
With eval('(' + json_object + ')'), you will be able to create a JavaScript Object. This object will be an array, and you can acess the properties using ..
For example, if your json_object is called data, for example:
Then
var temp = eval('(' + data + ')'); // temp now is an array.
if you want to access the first _index or id from the json object:
"_index": "test",
"id": "YMFT112",
do alert(temp[0]._index), and it will show you "test". For the other properties, follow the same logic. This stackoverflow question, or the JSON page will help you understand what you have to do in other to have your task accomplished. Yahoo has an API called YUI which may be even more helpful.
Here is a solution using object-scan
// const objectScan = require('object-scan');
const data = [{"_index":"test","id":"YMFT112","_source":{"Author":"SAM","Map":[{"count":1,"term":"Company","Company":[{"sector":"Technology","ticker":"AAPL","Apple_Inc":[{"count":1,"term":"Apple"}],"term":"Apple Inc","type":"BCap"}]},{"count":1,"term":"Country","Country":[{"region":"North Americas","index":"DOW JONES INDUS. AVG , S&P 500 INDEX , NASDAQ COMPOSITE INDEX","United_States":[{"count":1,"term":"United States"}],"term":"Canada","currency":"Dollar (USD)","Canada":[{"count":1,"term":"Canada","Canada":[{"count":1,"term":"Toronto"}]}]}]},{"count":5,"term":"Personality","Personality":[{"count":1,"term":"Bart Prince"},{"count":1,"term":"Thomas"},{"count":1,"term":"Deborah Hornstra"},{"count":1,"term":"Henderson Sotheby"},{"count":1,"term":"Max Alliance"}]}]},"Link":"http://testLink.com/1"},{"_index":"test","_id":"YMFT113","_source":{"Author":"MAX","Map":[{"count":1,"term":"Company","Company":[{"sector":"Technology","ticker":"AAPL","Microsoft Corp":[{"count":1,"term":"Microsoft"}],"term":"Microsoft","type":"BCap"}]},{"count":1,"term":"Country","Country":[{"region":"South Americas","Brazil":[{"count":1,"term":"Brazil"}],"term":"Brazil","currency":"Dollar (USD)"}]},{"SalesRelated":[{"count":1,"term":"traffic"}]},{"count":4,"term":"Personality","Personality":[{"count":1,"term":"Maximor"},{"count":1,"term":"R.V.P"},{"count":1,"term":"Wenger"},{"count":1,"term":"SAF"}]}]},"Link":"http://testLink.com/2"}];
const find = (term, input) => {
const r = objectScan([`[*]._source.Map[*].${term}[*].**.term`], {
reverse: false,
filterFn: ({ key, parents, context }) => {
if (Object.values(parents[0]).some((e) => e instanceof Object)) {
return;
}
const root = parents[parents.length - 2];
context.push([
root.id || root._id,
parents[parents.length - 5].term,
key[key.length - 3].replace(/_/g, ' '),
...parents.slice(0, -7).filter((e) => !Array.isArray(e)).map((p) => p.term).reverse(),
root.Link
]);
}
})(input, []);
const maxLength = Math.max(...r.map((e) => e.length));
r
.filter((e) => e.length < maxLength)
.forEach((e) => e.splice(-1, 0, 'NA'.repeat(maxLength - e.length)));
return r;
};
console.log(find('Country', data).map((e) => e.join('; ')).join('\n'));
/* =>
YMFT112; Country; United States; United States; NA; http://testLink.com/1
YMFT112; Country; Canada; Canada; Toronto; http://testLink.com/1
YMFT113; Country; Brazil; Brazil; NA; http://testLink.com/2
*/
console.log(find('Company', data).map((e) => e.join('; ')).join('\n'));
/* =>
YMFT112; Company; Apple Inc; Apple; http://testLink.com/1
YMFT113; Company; Microsoft Corp; Microsoft; http://testLink.com/2
*/
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan

Categories