Append JSON data at a specific index - javascript-objects

I'm trying to append the JSON data at a specific index but it's not working. The JSON data is-
a = {resourceTypeId: "tmf.resourceTypes.TmfServiceInterface", transitions: [2], states: null}
There are 2 arrays in transitions
transitions: [2]
0: {…}
stateFrom: "initial"
stateTo: "feasibilityChecked"
name: "checkFeasibility"
operationName: "checkServiceFeasibility"
1: {…}
stateFrom: "initial"
stateTo: "designed"
name: "design"
operationName: "designService"
I'm trying to append the 3rd array in transitions
b = {
"name": "deleteaaa",
"operationName": "Serviceaa",
"stateFrom": "test",
"stateTo": "test"
}
I've tried this-
c = a.transitions.concat(b)
It's adding the 3rd array in transitions but not getting Other data like resourceTypeId: "tmf.resourceTypes.TmfServiceInterface" and states: null
The expected data should be after merging b into a
c = {resourceTypeId: "tmf.resourceTypes.TmfServiceInterface", transitions: [3], states: null}
Pls, assist.

you maybe want this
a.transitions = a.transitions.concat(b)
var a = {
"resourceTypeId": "tmf.resourceTypes.TmfServiceInterface",
"transitions": [
{
"stateFrom": "initial",
"stateTo": "feasibilityChecked",
"name": "checkFeasibility",
"operationName": "checkServiceFeasibility"
},
{
"stateFrom": "initial",
"stateTo": "designed",
"name": "design",
"operationName": "designService"
},
{
"name": "deleteaaa",
"operationName": "Serviceaa",
"stateFrom": "test",
"stateTo": "test"
}
],
"states": null
}
var b = {
"name": "deleteaaa",
"operationName": "Serviceaa",
"stateFrom": "test",
"stateTo": "test"
}
a.transitions = a.transitions.concat(b)
console.log(a)
example

Related

How to parse a nested json file in typescript (.tsx)?

I'm new to typescript and looking for a way to parse this nested json data given below and display the following info after parsing:
Date: 2022-10-27T16:28:01Z
Typename": Asset,
PolicyId: 12345678abcdef,
Asset Name: 12345678abc,
Quantity:5000,
Output txHash: 1212345678abcdef,
Output txHash: 1212345678abcdef1234
{
"transactions": [
{
"__typename": "Transaction",
"includedAt": "2022-10-27T16:28:01Z",
"mint": [
{
"__typename": "Token",
"asset": {
"__typename": "Asset",
"policyId": "12345678abcdef",
"assetName": "12345678abc",
"name": null
},
"quantity": "5000"
}
],
"outputs": [
{
"__typename": "TransactionOutput",
"txHash": "1212345678abcdef",
"value": "1500000",
"tokens": [
{
"__typename": "Token",
"asset": {
"__typename": "Asset",
"policyId": "12345678abcdef",
"assetName": "12345678abc"
},
"quantity": "5000"
}
]
},
{
"__typename": "TransactionOutput",
"txHash": "12bcd12345678abcdef1234",
"value": "9998312015",
"tokens": []
}
]
}
]
}
`
I tried the following code:
const myJSON = JSON.stringify(data, null, 2);
const myArray = JSON.parse(myJSON);
and was able to display the Date:
const DisplayData1 = myArray.transactions.map(
(info:any) => {
return(
<tr>
<td>{info.includedAt}</td>
</tr>
)
}
)
I'm not able to proceed due to the nested nature of the json file and my lack of familiarity with tsx. All help appreciated. Thanks.
Need to add the nested loop to show data.
Also in order to access keys starting with -, use a square bracket instead of the . operator. like obj['__typename']
const DisplayData1 = myArray.transactions.map(
(info:any) => {
return(
<tr>
<td>{info.includedAt}</td>
{
info.mint.map((i) => {
return (
<td>{i['__typename']}</td>
<td>{i.quantity}</td>
<td>{i.asset.policyId}</td> // access `asset` object
)
})
}
</tr>
)
}
)

React Native - Sort array based off words

Hey guys i have the following array:
Array [
Object {
"data": "Cat Man",
"id": "1",
},
Object {
"data": "Bat Girl",
"id": "2",
},
Object {
"data": "Mr Penguin",
"id": "3",
},
Object {
"data": "Cheeky Cheetah",
"id": "4",
},
]
I am going to take the users input in the form of a search bar, how can i sort the array based off the users input.
So lets say the user inputs
Bat g
the array would be sorted to:
Array [
Object {
"data": "Bat Girl",
"id": "2",
},
Object {
"data": "Cat Man",
"id": "1",
},
Object {
"data": "Mr Penguin",
"id": "3",
},
Object {
"data": "Cheeky Cheetah",
"id": "4",
},
]
How can I achieve this?
I have been searching around the array sort function:
Array.prototype.sort()
However I have only seen how to sort based off number comparisons I have never seen an array sorted based off string values like a search. Please could someone help me with this!
Here is function to search data using string text.
const searchItem = txt => {
let text = txt.toLowerCase();
let tracks = dataArray;
let filterTracks = tracks.filter(item => {
if (item.data.toLowerCase().match(text)) {
return item;
}
});
console.log('filterTracks', filterTracks);
};
Array Should be like this
var dataArray = [
{
data: 'Cat Man',
id: '1',
},
{
data: 'Bat Girl',
id: '2',
},
{
data: 'Mr Penguin',
id: '3',
},
{
data: 'Cheeky Cheetah',
id: '4',
},
];

Mule 4 - How to combine arrays inside a nested array with the same id field into one

Suppose I have the following payload with nested array, how do I combine the array inside the nested array for the same externalId as well as some logic on certain field like
shipQty - this field will be sum or add up for records with the same externalId under fillingOrder
serialNumbers - all the records under serialNumbers will be display together if the externalId is same
Kindly refer below for the input and expected output
Json Payload Input
{
"Identifier": "9i098p-898j-67586k",
"transactionDate": "2019-09-08T10:01:00-04:00",
"order": [
{
"orderNumber": "123456789",
"CourierOrderId": "1300-88-2525",
"fillingOrder": [
{
"numberOfBoxes": 0,
"tracking": [
{
"carrier": "Orange",
"trackNum": "3333444",
"trackUrl": "https://www.orange.com/track/status",
"shipDate": "2019-09-08T10:01:00-04:00",
"SerialNumber": "00000123"
}
],
"row": [
{
"externalId": "1",
"unitNo": "OP04-123456-789",
"shipQty": 2,
"serialNumbers": [
{
"serialNumber": "USD333555",
"quantity": 1
},
{
"serialNumber": "USD235678",
"quantity": 1
}
]
}
]
},
{
"tracking": [
{
"carrier": "Apple",
"trackNum": "555666",
"trackUrl": "https://www.apple.com/track/status",
"shipDate": "2019-09-08T10:01:00-04:00",
"SerialNumber": "00000645"
}
],
"row": [
{
"externalId": "1",
"unitNo": "OP04-123456-789",
"shipQty": 3,
"serialNumbers": [
{
"serialNumber": "USD123456",
"quantity": 1
},
{
"serialNumber": "USD98765",
"quantity": 1
},
{
"serialNumber": "USD45689",
"quantity": 1
}
]
}
]
},
{
"tracking": [
{
"carrier": "banana",
"trackNum": "587390",
"trackUrl": "https://www.banana.com/track/status",
"shipDate": "2019-09-08T10:01:00-04:00",
"SerialNumber": "00000365"
}
],
"row": [
{
"externalId": "2",
"unitNo": "OP05-123456-111",
"shipQty": 2,
"serialNumbers": [
{
"serialNumber": "USD00045",
"quantity": 1
},
{
"serialNumber": "USD00046",
"quantity": 1
}
]
}
]
}
]
}
]
}
Expected Json Output
{
"row": [
{
"externalId": "1",
"unitNo": "OP04-123456-789",
"shipQty": 5, //the shipQty should be add up when the externalId is same
"serialNumbers": [ //the serialNumbers should display all the data inside the serialNumbers when the externalId is same
{
"serialNumber": "USD333555",
"quantity": 1
},
{
"serialNumber": "USD235678",
"quantity": 1
},
{
"serialNumber": "USD123456",
"quantity": 1
},
{
"serialNumber": "USD98765",
"quantity": 1
},
{
"serialNumber": "USD45689",
"quantity": 1
}
]
},
{
"externalId": "2",
"unitNo": "OP05-123456-111",
"shipQty": 2,
"serialNumbers": [
{
"serialNumber": "USD00045",
"quantity": 1
},
{
"serialNumber": "USD00046",
"quantity": 1
}
}
]
}
It looks like you only need the data of "row" inside the fillingOrder field of your payload. So first thing to simplicy the problem is to get all the rows as a single array. Once you have that them you just need to group that by external id and the problem will start to look smaller.
%dw 2.0
output application/json
//First get all rows since it looks like you only need them.
//If you find this confusing try to use flatten with some simpler payloads.
var allRows = flatten(flatten(payload.order.fillingOrder).row)
//Group them according to external id.
var groupedExtId = allRows groupBy $.externalId
---
{
row: groupedExtId pluck ((value, extId, index) -> do {
var sumShipQuant = sum(value.shipQty default [])
---
{
externalId: (extId), //the key after grouping is external id
unitNo: value.unitNo[0], //assuming it is same across diff external id
shipQty: sumShipQuant,
serialNumbers: flatten(value.serialNumbers) //Flatten because value is an array and it has multiple serielNumbers array
}
})
}
This should help. I took some inspiration from Harshank Bansal post
%dw 2.0
output application/json
var groupFlat = flatten(flatten (payload.order.fillingOrder).row) groupBy ($.externalId)
---
row: [groupFlat mapObject ((value, key, index) -> {
externalId: value.externalId[0],
unitNO: value.unitNo[0],
shipQty: sum(value.shipQty),
serialNumbers: flatten(value.serialNumbers)
})]
Try this:
%dw 2.0
output application/json
---
row:[ if (payload..order..row..externalId[0] == payload..order..row..externalId[1]) {
externalId : payload..order..row..externalId[0],
unitNo: payload..order..row..unitNo[0],
shipQty: payload..order..row..shipQty[0] + payload..order..row..shipQty[1],
serialNumbers: flatten (payload..order..row..serialNumbers)
}
else null]

Return one array of data in sub-document of Mongodb

I'm using Nodejs with Mongoose package.
Given I've something like this:-
let people = [
{
"_id": 1,
"name": "Person 1",
"pets": [
{
"_id": 1,
"name": "Tom",
"category": "cat"
},
{
"_id": 2,
"name": "Jerry",
"category": "mouse"
}
]
}
]
I want to get only the data of Jerry in pets array using it's _id (result shown below)
{
"_id": 2,
"name": "Jerry",
"category": "mouse"
}
Can I get it without needing to specify the _id of person 1 when using $elemMatch? Right now I code like this:-
const pet = People.find(
{ "_id": "1"}, // specifying 'person 1 _id' first
{ pets: { $elemMatch: { _id: 2 } } } // using 'elemMatch' to get 'pet' with '_id' of '2'
)
And it gave me what I want like I've shown you above. But is there any other way I can do this without needing to specify the _id of it's parent first (in this case, the _id of the people array)
Assuming nested array's _id's are unique you can filter by nested array elements directly:
const pet = People.find(
{ "pets._id": 2 },
{ pets: { $elemMatch: { _id: 2 } } }
)

In Mongoose, query fields based on array

I am trying to query documents from a mongodb collection, based on array of input query parameters sent from URL.
Sample Database Data
[
{
"drawings": {
"circle": [],
"square": [
{
"id": "828",
"name": "square"
}
],
"cube": []
},
{
"drawings": {
"circle": [
{
"id": "827",
"name": "circle"
}
],
"square": [],
"cube": []
},
{
"drawings": {
"circle": [],
"square": [],
"cube": [
{
"id": "829",
"name": "cube"
}
]
}
]
Input Query Parameter:
query = ["square","cube"];
Expected Output:
[
{
"drawings": {
"circle": [],
"square": [
{
"id": "828",
"name": "square"
}
],
"cube": []
},
{
"drawings": {
"circle": [],
"square": [],
"cube": [
{
"id": "829",
"name": "cube"
}
]
}
]
Best suited Mongoose Query:
Schema.find({
$or:[
{'drawings.square':{$elemMatch:{ name:'square'}}},
{'drawings.cube':{$elemMatch:{ name:'cube'}}}
]
});
Tried Below method. But, it is not correct.
let draw = ["square","cube"];
let draw_query =[];
for (let a=0; a<draw.length;a++){
draw_query.push("{\"drawings."+ draw[a] +"\':{$elemMatch:{ name:\"" + draw[a] + "\"}}}");
}
It creates array with single quoted strings. It cannot be used.
[ '{"drawings.square":{$elemMatch:{ name:"square"}}}',
'{"drawings.cube":{$elemMatch:{ name:"cube"}}}' ]
How to generate this mongoose query dynamically? or is there any better mongoose query to achieve the expected result.
You can query it directly using dot notation so the query should look like below:
db.collection.find({
$or: [
{
"drawings.square.name": "square"
},
{
"drawings.circle.name": "circle"
}
]
})
You can build it in JS using .map(), try:
var query = ["square","cube"];
var orQuery = { $or: query.map(x => ({ [x + ".name"]: x }) ) }

Resources