Displaying JSON multi-dimensional array data with ReactJS and map - javascript

I have some multi-dimensional JSON data that contains different clothing items, each clothing item containing its own array of information.
I am trying to display this as such, using ReactJS:
{Product Name}
{size 1} has {quantity 1} in stock
{size 2} has {quantity 2} in stock
{size 3} has {quantity 3} in stock
My JSON looks like this:
{
"myShirt": [
{
"size": "Small",
"quantity": 0,
},
{
"size": "Medium",
"quantity": 0,
},
{
"size": "Large",
"quantity": 0,
},
],
"myShirt2": [
{
"size": "Small",
"quantity": 0,
},
{
"size": "Medium",
"quantity": 0,
},
{
"size": "Large",
"quantity": 0,
},
],
"myShirt3": [
{
"size": "Small",
"quantity": 0,
},
{
"size": "Medium",
"quantity": 0,
},
{
"size": "Large",
"quantity": 0,
},
]
}
So for example, in this case my desired output would be:
myShirt
Small has 0 in stock
Medium has 0 in stock
Large has 0 in stock
myShirt2
Small has 0 in stock
Medium has 0 in stock
Large has 0 in stock
myShirt3
Small has 0 in stock
Medium has 0 in stock
Large has 0 in stock
I have created a React component that includes this JSON data as part of its state. This component looks like this:
class Products extends React.Component {
constructor() {
super();
this.state = {
data: [
{
"myShirt": [
{
"size_text": "Small",
"quantity": 0,
},
{
"size_text": "Medium",
"quantity": 0,
},
{
"size_text": "Large",
"quantity": 0,
},
],
"myShirt2": [
{
"size_text": "Small",
"quantity": 3,
},
{
"size_text": "Medium",
"quantity": 0,
},
{
"size_text": "Large",
"quantity": 0,
},
],
"myShirt3": [
{
"size_text": "Small",
"quantity": 3,
},
{
"size_text": "Medium",
"quantity": 0,
},
{
"size_text": "Large",
"quantity": 0,
},
]
}]
}
}
render() {
return (
<div>
{
// HOW DO I DISPLAY MY OUTPUT HERE?
}
</div>
);
}
}
My approach to displaying my output was using .map. However, the bare code I used to do this wasn't successful. It looked like this:
render() {
return (
<div>
{
this.state.data.map((product, i) =>
<p>{product.map((productData, j) =>
<span>{productData.size_text}</span>
)
}</p>
)
}
</div>
);
}
This code doesn't attempt to display the entire output as I was just testing out the waters to see if I could get anything, at least a size to display. As you can tell, I'm pretty much stuck in the render function of the component. I don't know how I would access the product name, and moreover the product size name and quantity.
How would you go about solving this to get it to look like the desired output?
Thanks!

You can use Object.keys() to iterate through each key of state and then use array#map to iterate each array object.
class Products extends React.Component {
constructor() {
super();
this.state = { "myShirt": [ { "size_text": "Small", "quantity": 0 }, { "size_text": "Medium", "quantity": 0 }, { "size_text": "Large", "quantity": 0}, ], "myShirt2": [ { "size_text": "Small", "quantity": 3 }, { "size_text": "Medium", "quantity": 0}, { "size_text": "Large", "quantity": 0}, ], "myShirt3": [ { "size_text": "Small", "quantity": 3 }, { "size_text": "Medium", "quantity": 0}, { "size_text": "Large", "quantity": 0}, ] }
}
render() {
return (<div>{Object.keys(this.state).map(k => {
return <div>{k}<div>{
this.state[k].map(o => <div className={'left'}>{`${o.size_text} has ${o.quantity} in stock`}</div>)
}</div></div>
})}</div>)
}
}
ReactDOM.render(<Products />, document.getElementById('root'));
.left {
margin-left: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'></div>

Well, I would've done it this way.
You can check console for logged values in desired format.
Now, I expect, you can add these values in your template yourself :)
Thanks
var stock = {
"myShirt": [
{
"size": "Small",
"quantity": 0,
},
{
"size": "Medium",
"quantity": 0,
},
{
"size": "Large",
"quantity": 0,
},
],
"myShirt2": [
{
"size": "Small",
"quantity": 0,
},
{
"size": "Medium",
"quantity": 0,
},
{
"size": "Large",
"quantity": 1,
},
],
"myShirt3": [
{
"size": "Small",
"quantity": 0,
},
{
"size": "Medium",
"quantity": 0,
},
{
"size": "Large",
"quantity": 0,
},
]
}
Object.keys(stock).map(e=>{
console.log(e+":");
stock[e].map(o=> console.log(o.size +" has "+o.quantity+" in stock"))
})

Thanks everyone for your comments!
To solve this I used a combination of two of the answers, and made my render function looks as such:
render() {
return (
<div id="product-container">{Object.keys(this.state.data).map(productId => {
return <div id="product-info">
<h2>{productId}</h2>
<div id="product-line-detail">{
this.state.data[productId].map(productDetail => <div className={'left'}>{`${productDetail.size_text} has ${productDetail.quantity} in stock`}</div>)
}
</div>
</div>
})}
</div>
)
}

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

how can I search such tree structure by value in typescript without getting maximum stack call exceeded

how can I search such tree structure by value in typescript without getting maximum stack call exceeded.
I am trying to search an expandable tree using typescript , I will attach the code I am trying down below
tree= [
{
"size": -1320,
"offset": 0,
"value": "E",
"subNodes": [
{
"size": 48,
"offset": 0,
"value": "D"
},
{
"size": 48,
"offset": 0,
"value": "D"
},
{
"size": 48,
"offset": 0,
"value": "D"
}
],
{
"size": -1320,
"offset": 0,
"value": "E",
"subNodes": [
{
"size": 48,
"offset": 0,
"value": "D"
},
{
"size": 48,
"offset": 0,
"value": "D",
"subNodes": [
{
"size": 48,
"offset": 0,
"value": "D"
},
{
"size": 48,
"offset": 0,
"value": "D"]
}]]
and I am getting maximum call stack reached! I am not sure why , is it due to the recursive call of the function? is it possible to search with just letters of the value ?
here is my code :
searchTree(protcolTree: Array<SessionTree>, searchString: string): Array<SessionTree> {
if (this.protocolTree[0].value === searchString) {
this.protocolTree = protcolTree;
} else if (this.protocolTree.length) {
let result: Array<SessionTree> = null;
for (let i = 0; result === null && i < this.protocolTree.length; i++) {
result = this.searchTree(this.protocolTree[i].subNodes, searchString);
}
this.protocolTree = result;
return result;
}
return this.protocolTree;
}
searchTreeNodes(tree: Array<SessionTree>, searchString: string): void {
this.protocolTree.filter(node => node.value === searchString);
}

how to filter array of object in Javascript es6

I want to filter items from the schedule variable based on "isPackageIncluded"
"isPackageIncluded": 1 then only the data that is "isPackageIncluded": 1 is displayed if the data is not displayed, I have tried filtering it but it still doesn't work,all data remains displayed, what is the solution for this case, please help, thank you
let schedule = [
{
"tempRfpScheduleId": "12345",
"package": {
"tempRfpSchedulePackageId": "888",
"totalAttendees": 0
},
"food": [
{
"tempRfpScheduleFoodId": "123",
"foodName": "Test",
"quantity": 0,
"isPackageIncluded": 1
},
{
"tempRfpScheduleFoodId": "456",
"foodName": "Coffee Break",
"quantity": 0,
"isPackageIncluded": 0
}
],
"accomodation": [
{
"tempRfpScheduleAccomodationId": "111",
"quantity": 0,
"isPackageIncluded": 1
},
{
"tempRfpScheduleAccomodationId": "222",
"quantity": 0,
"isPackageIncluded": 0
}
]
},
{
"tempRfpScheduleId": "67890",
"package": {
"tempRfpSchedulePackageId": "999",
"totalAttendees": 0
},
"food": [
{
"tempRfpScheduleFoodId": "1122",
"quantity": 0,
"isPackageIncluded": 0
},
{
"tempRfpScheduleFoodId": "3344",
"quantity": 0,
"isPackageIncluded": 1
}
],
"accomodation": [
{
"tempRfpScheduleAccomodationId": "444",
"quantity": 0,
"isPackageIncluded": 0
},
{
"tempRfpScheduleAccomodationId": "555",
"quantity": 0,
"isPackageIncluded": 1
}
]
}
]
Expected result
schedule = [
{
"tempRfpScheduleId": "12345",
"package": {
"tempRfpSchedulePackageId": "888",
"totalAttendees": 0
},
"food": [
{
"tempRfpScheduleFoodId": "123",
"foodName": "Test",
"quantity": 0,
"isPackageIncluded": 1
}
],
"accomodation": [
{
"tempRfpScheduleAccomodationId": "111",
"quantity": 0,
"isPackageIncluded": 1
}
]
},
{
"tempRfpScheduleId": "67890",
"package": {
"tempRfpSchedulePackageId": "999",
"totalAttendees": 0
},
"food": [
{
"tempRfpScheduleFoodId": "3344",
"quantity": 0,
"isPackageIncluded": 1
}
],
"accomodation": [
{
"tempRfpScheduleAccomodationId": "555",
"quantity": 0,
"isPackageIncluded": 1
}
]
}
]
this lies in a function, but the results are not as expected, do I have to loop the array first and then filter it after the array is looped?
const _handleSubmit = event => {
event.preventDefault()
schedule.map((item, index) => {
item.food.map(itemFood => itemFood.isPackageIncluded > 0)
item.accomodation.map(itemAccomondation => itemAccomondation.isPackageIncluded > 0)
})
}
``
You were close. In your map(), item is each array element, so you don't need to use the [index] bit. Next, you were correct, filter() inside the map. But you'll need to assign the original item.food and item.accomodation with the filtered values.
Here you go:
let schedule = [{"tempRfpScheduleId":"12345","package":{"tempRfpSchedulePackageId":"888","totalAttendees":0},"food":[{"tempRfpScheduleFoodId":"123","foodName":"Test","quantity":0,"isPackageIncluded":1},{"tempRfpScheduleFoodId":"456","foodName":"Coffee Break","quantity":0,"isPackageIncluded":0}],"accomodation":[{"tempRfpScheduleAccomodationId":"111","quantity":0,"isPackageIncluded":1},{"tempRfpScheduleAccomodationId":"222","quantity":0,"isPackageIncluded":0}]},{"tempRfpScheduleId":"67890","package":{"tempRfpSchedulePackageId":"999","totalAttendees":0},"food":[{"tempRfpScheduleFoodId":"1122","quantity":0,"isPackageIncluded":0},{"tempRfpScheduleFoodId":"3344","quantity":0,"isPackageIncluded":1}],"accomodation":[{"tempRfpScheduleAccomodationId":"444","quantity":0,"isPackageIncluded":0},{"tempRfpScheduleAccomodationId":"555","quantity":0,"isPackageIncluded":1}]}]
let out = schedule.map((item, index) => {
item.food = item.food.filter(itemFood => itemFood.isPackageIncluded > 0)
item.accomodation = item.accomodation.filter(itemAccomondation => itemAccomondation.isPackageIncluded > 0)
return item;
})
console.log(out);

How to move element in nested array

i wanted to move element in nested array. so, here this my data:
let products = [
{
"product_name": "A",
"_id": "5ace995c14a759325776aab1",
"transactions": [
{
"_id": "5ad3a274ac827c165a510f99",
"qty": 100,
"price": 2000
},
{
"_id": "5ad3a274ac827c165a510f99",
"qty": 80,
"price": 1500
},
]
},
{
"product_name": "B",
"_id": "5ace995914a759325776aab0",
"transactions": [
{
"_id": "5ad3a274ac827c165a510f9b",
"qty": 80,
"price": 1500
}
],
}
]
The output that i expected:
[
{
"_id": "5ad3a274ac827c165a510f99",
"qty": 100,
"price": 2000,
"product_name": "A",
},
{
"_id": "5ad3a274ac827c165a510f99",
"qty": 80,
"price": 1500,
"product_name": "A",
},
{
"_id": "5ad3a274ac827c165a510f9b",
"qty": 80,
"price": 1500,
"product_name": "B",
}
]
then, my solve code:
function move() {
var result = []
for (product of products) {
for (transaction of product.transactions) {
transaction.product_name = product.product_name
result.push(transaction)
}
}
return result
}
product = move()
Is there any effective way to create the output, maybe with array map or anything else? Thank you.
You could flat the transactions with Array#reduce and using Object.assign for adding product_name.
Also used:
destructuring assignment for the properties and
short hand properties for taking a variable as property with the name as key.
var products = [{ product_name: "A", _id: "5ace995c14a759325776aab1", transactions: [{ _id: "5ad3a274ac827c165a510f99", qty: 100, price: 2000 }, { _id: "5ad3a274ac827c165a510f99", qty: 80, price: 1500 }] }, { product_name: "B", _id: "5ace995914a759325776aab0", transactions: [{ _id: "5ad3a274ac827c165a510f9b", qty: 80, price: 1500 }] }],
result = products.reduce((r, { transactions, product_name }) =>
r.concat(transactions.map(t => Object.assign({}, t, { product_name }))),
[]
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can reduce and map the transactions to add the product name
let result = products.reduce((c,v)=>{ //Loop the array using reduce
let transactions = v.transactions.map(o=>{ //Loop thru each transactions using map
return Object.assign(o,{"product_name":v.product_name}); //Clone the transaction and add the property product_name
});
return c.concat(transactions); //Merge the current array and the transactions
},[]);
Here is a snippet:
//Your array
let products=[{"product_name":"A","_id":"5ace995c14a759325776aab1","transactions":[{"_id":"5ad3a274ac827c165a510f99","qty":100,"price":2000},{"_id":"5ad3a274ac827c165a510f99","qty":80,"price":1500},]},{"product_name":"B","_id":"5ace995914a759325776aab0","transactions":[{"_id":"5ad3a274ac827c165a510f9b","qty":80,"price":1500}],}]
//The short version
let result = products.reduce((c, v) => c.concat(v.transactions.map(o =>Object.assign(o, {"product_name": v.product_name}))), []);
console.log(result);
Just using js methods you can have your desired output
const products = [
{
"product_name": "A",
"_id": "5ace995c14a759325776aab1",
"transactions": [
{
"_id": "5ad3a274ac827c165a510f99",
"qty": 100,
"price": 2000
},
{
"_id": "5ad3a274ac827c165a510f99",
"qty": 80,
"price": 1500
},
]
},
{
"product_name": "B",
"_id": "5ace995914a759325776aab0",
"transactions": [
{
"_id": "5ad3a274ac827c165a510f9b",
"qty": 80,
"price": 1500
}
],
}
]
let output =[];
products.forEach(elm => elm.transactions.forEach(transaction => {
transaction.product_name = elm.product_name;
output.push(transaction)}));
console.log(output);

Compare two arrays of objects and filter results

Example:
const depositAddress = '2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG';
DBarray1.forEach( (tx) => {
console.log(tx);
})
TXarray2.forEach( (sim) => {
console.log(sim);
});
DBarray1 = [
{
"_id": "575e2b7875a402111900ba8f",
"username": "aleluia#gmail.com",
"playerWallet": "2NFt8YfydBU5JD9U8Xq2ucbfUp2sP7BjUrh",
"User_Profile": {
"TXHash": [
"7fbe28f75412f19dfd123a08ce03c33c302aa13d1e68d38ab8cb4c7418777f8e"
]
}
},
{
"_id": "575e2946b909906a17ea65b9",
"username": "super#user.com",
"playerWallet": "2MzppxEX7xMidjhoJGczFDYsHk5TQwFkjS3",
"User_Profile": {
"TXHash": [
"cf948340a40d3302303dfb3710cfce37bb1cd156dcb6c74561fdc71c0a8fc30b",
"6219def49d2e8284a6031f4c7e05e21adf756d38904e6359bd7844ae14c75a50"
]
}
}
] // end console.log(DBarray1);
TXarray2 = [
{
"id": "cf948340a40d3302303dfb3710cfce37bb1cd156dcb6c74561fdc71c0a8fc30b",
"normalizedHash": "f62af1a61c7eb569c1a171ad23c70bc218bd7244c9c5c92cf7d98638314fbbc5",
"date": "2016-06-21T04:11:18.541Z",
"fee": 6280,
"inputs": [
{
"previousHash": "2660fb761354671912b0cea6427e9ee91a98a507e5f1408865a6058b566b508c",
"previousOutputIndex": 0
},
{
"previousHash": "ce3ef138c11ea4d1766cce52ccf5f1e91790bc03b56561b0eb669041bae4e1a3",
"previousOutputIndex": 0
}
],
"outputs": [
{
"vout": 0,
"account": "2N92kApgroS6CTVuTajtjWtpcAZpUiyQoDT",
"value": 861003
},
{
"vout": 1,
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 3100000,
"isMine": true,
"chain": 0,
"chainIndex": 0
}
],
"entries": [
{
"account": "2MzppxEX7xMidjhoJGczFDYsHk5TQwFkjS3",
"value": -3967283
},
{
"account": "2N92kApgroS6CTVuTajtjWtpcAZpUiyQoDT",
"value": 861003
},
{
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 3100000
}
],
"confirmations": 70,
"pending": false,
"instant": true,
"instantId": "5768be65427689eb06e597559c7e6cf0",
"blockhash": "00000000002d9fb51c7c3c1607fe062eff686aa6be657a59fee6c3044963897d",
"height": 872152
},
{
"id": "6219def49d2e8284a6031f4c7e05e21adf756d38904e6359bd7844ae14c75a50",
"normalizedHash": "179a4466fdfc5470e99e43aa177d43aa4f09e3a06760fd5bebffdda080d4407f",
"date": "2016-06-21T04:13:23.650Z",
"fee": 9096,
"inputs": [
{
"previousHash": "5d2879a79ea3d0dcb50049ef9ca46ef7e8d82caf2073a299a6cd0332add404c8",
"previousOutputIndex": 1
},
{
"previousHash": "d75288e69a3fc2edd534ddcd845af6a280a27af58013ae82828c8a8f813829c1",
"previousOutputIndex": 0
},
{
"previousHash": "eea4f9b274708b60c1b030203543a155857bc54aa11055ada04aceee706f96b9",
"previousOutputIndex": 0
}
],
"outputs": [
{
"vout": 0,
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 2000000,
"isMine": true,
"chain": 0,
"chainIndex": 0
},
{
"vout": 1,
"account": "2MzFTm5jnCDiAapjNnyVgZAJrXMKfQ74esV",
"value": 9859
}
],
"entries": [
{
"account": "2MzcwVFKF274bMNT5tNEDY7Ua7bAgvFUdu9",
"value": -35316
},
{
"account": "2MzFTm5jnCDiAapjNnyVgZAJrXMKfQ74esV",
"value": 9859
},
{
"account": "2MzppxEX7xMidjhoJGczFDYsHk5TQwFkjS3",
"value": -1983639
},
{
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 2000000
}
],
"confirmations": 70,
"pending": false,
"instant": true,
"instantId": "5768bee2b5bdf3f406e7db035aef016a",
"blockhash": "00000000002d9fb51c7c3c1607fe062eff686aa6be657a59fee6c3044963897d",
"height": 872152
},
{
"id": "7fbe28f75412f19dfd123a08ce03c33c302aa13d1e68d38ab8cb4c7418777f8e",
"normalizedHash": "b4f1974dccde5ea9dfb0abcd7d4a6f3f14995d9dd422aa7d2a9078229ff18ff4",
"date": "2016-06-21T03:39:25.034Z",
"fee": 3465,
"inputs": [
{
"previousHash": "97fbb6ed8646f7ce9ed10a4230a70348151d5b6b208ad068e3a1a3fddae2dc0e",
"previousOutputIndex": 2
}
],
"outputs": [
{
"vout": 0,
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 111200000,
"isMine": true,
"chain": 0,
"chainIndex": 0
},
{
"vout": 1,
"account": "2NFJnLrhsCDfG3ooQvGC169gnzBabtRgV2y",
"value": 244246993
}
],
"entries": [
{
"account": "2NCGUnwpNgaJbhMZKLJcBrWvZhWnai5PjVC",
"value": -355450458
},
{
"account": "2NFJnLrhsCDfG3ooQvGC169gnzBabtRgV2y",
"value": 244246993
},
{
"account": "2NBXPR5PRtW8xBRuDnWXBDXqHYpDPupWnhG",
"value": 111200000
}
],
"confirmations": 77,
"pending": false,
"instant": false,
"blockhash": "0000000000509dbc80cc3d86cdb10ce8e87ab7867c6775a9b00ca904fbe70da7",
"height": 872145
}
]// end console.log(TXarray2);
How can we check if TXarray2.id which is the transactions id, if it matches a payment made by the user inside DBarray1.User_Profile.TXHash for examplecf948340a40d3302303dfb3710cfce37bb1cd156dcb6c74561fdc71c0a8fc30b .
I want to know forEach TXarray2.id who made the payment . I tried to do this with promises and i will share some code when i get home but i'm sure it can be done with async for all users one by one and log who made a payment today to this wallet. I tried with array.find() method to check inside TXHash but failed, i don't fully grasp many prototype methods yet...
Hopefully someone already thinks this a walk on the park for him and found a better solution to validate this kind of stuff. I will accept any answer even with lodash, maping, anything. TY !!!
You iterate TXArray2 and do a lookup in DBarray1 for the transactionId.
I like to work with native array methods like map and filter, so I would use something like the following:
const result = TXarray2.map(tx => ({
transaction: tx,
user: DBarray1.filter(user => user.User_Profile.TXHash.indexOf(tx.id) > -1)[0]
}));
In this example result is an array where every element contains a transaction and the matching user.
If you already have all of the transaction and user data, could you do something like this?
// for each transaction in TXarray2
for (let { 'id': transactionId } of TXarray2) {
// check each entry in DBarray1
for (let { '_id': userId, 'User_Profile': { 'TXHash': transactions } } of DBarray1) {
if (transactions.includes(transactionId)) {
console.log(`${transactionId} was made by ${userId}`);
}
}
}
The best way here is to use Array.indexOf (or Array.findIndex if you want to use callbacks) which returns -1 if an entry is not in an array.
Here's the sync variant:
var paid = [];
TXArray2.forEach(function(transaction){
for(var i = 0; i < DBArray1.length; ++i){
if(DBArray1[i].User_Profile.TXHash.indexOf(transaction.id) > -1){
paid.push({
user : DBArray1[i],
transaction : transaction
});
break;
}
}
});
console.log(paid);

Categories