Iterate through array of objects,not giving required output - javascript

given code
[
{
"data": [
{
"text_name": "test",
"text_url": "https://www.news18.com/topics/gold-prices/1",
"is_new": "1"
},
{
"text_name": "test2",
"text_url": "https://www.news18.com/topics/gold-prices/2",
"is_new": "0"
}
],
"slug": "bollywood",
"heading": "testing",
"status": "1",
"is_open_new": "1",
"order_data": "2",
"section_dropdown": "bollywood"
}
]
I want to iterate through this given code snippet and get the data.
const trendingTopicsData = trendingTopics.data
but this is showing null

Since the object in the snippet is an array, first you have to get the index of the item you want to work with (in this case the first item — index 0). Then you can iterate through the data array however you want (loop, forEach, map etc.).
Try:
const trendingTopicsData = trendingTopics[0].data
Here it is as a runnable snippet:
const trendingTopics = [
{
"data": [
{
"text_name": "test",
"text_url": "https://www.news18.com/topics/gold-prices/1",
"is_new": "1"
},
{
"text_name": "test2",
"text_url": "https://www.news18.com/topics/gold-prices/2",
"is_new": "0"
}
],
"slug": "bollywood",
"heading": "testing",
"status": "1",
"is_open_new": "1",
"order_data": "2",
"section_dropdown": "bollywood"
}
]
// Get trending topics data array
const trendingTopicsData = trendingTopics[0].data;
console.log("Data array:", trendingTopicsData)
// Iterate through each of the items in the data array
trendingTopicsData.forEach((dataItem, index) => console.log(`Data item #${index}:`, dataItem));

The object you are trying to access is inside an array. You will have to loop through the array
trendingTopics.forEach(topic => {
// do something with topic.data
})

Related

is it possible to retrieve and print the data from a json object inside json array without using any index values and specific keys

[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
now i need to check and print the JSON Object inside the JSON Array if category is present then it should print and in future if category is changed according to that if we pass parameter the output should print we don't hard code the code
i have tried by using key values it is coming but if the key value changes it is not printing the object
EX:-
[
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}}]
in the above code i have printed category object but if category changed to categories it is not printing so i want a code which can read the code and based on parameters user giving it should be print the output
Try this.
For Example:
let a = [{"id": "628ba44f5a6de600071d16fa","category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}]}]
function print (values){return (a[0][`${values}`])}
//now just pass any name like "category" or in future "categories"
print("category") //this will retrun the array.
Now modify with your requirements.
It seems you want to get the value of the key(that can be parameterized).
const jsonArray = [
{
"id": "628ba44f5a6de600071d16fa",
"#baseType": "LogicalResource",
"isBundle": false,
"isMNP": false,
"businessType": [],
"category": [
{
"id": "628ba3ef5a6de600071d165f",
"name": "Starterpack2",
"description": "Starterpack2",
"code": "RC17",
"version": 2
}
]
}
];
const parameter = "category";
const result = jsonArray.find(({ [parameter]: value }) => value);
if (result) {
console.log(result);
} else {
console.log(`No object found with ${parameter}`);
}
If this is not what you are looking for, then please add your code snippet for better understanding.

Sort Object inside two arrays by ascending/descending

So I need to add sort functionality to the fuel.name value inside this array...
const orders = [
{
"_id":"5d14a31490fb1e0012a3d2d8-1",
"orderId":"0JL5ORM0JT-1",
"created":"2019-06-27T11:05:56.377Z",
"createdDate":"2019-06-27T09:05:56.377Z",
"offers":[
{
"price":95.27,
"fuel":{
"_id":"5ce13948eaef5200113b0de8",
"name":"Diesel B7",
"description":"Diesel",
"lpt":0,
"duty":0,
"type":"SPOT",
"created":"2019-05-19T11:08:56.417Z"
}
},
{
"price": 95.27,
"fuel": {
"_id": "5ce13948eaef5200113b0de8",
"name": "Petrol",
"description": "Petrol",
"lpt": 0,
"duty": 0,
"type": "SPOT",
"created": "2019-05-19T11:08:56.417Z"
}
},
{
"price": 95.27,
"fuel": {
"_id": "5ce13948eaef5200113b0de8",
"name": "Fossil Fuel",
"description": "Fossil Fuel",
"lpt": 0,
"duty": 0,
"type": "SPOT",
"created": "2019-05-19T11:08:56.417Z"
},
}
]
}
]
I want the "offers" object to reorder based on the "fuel.name"
orders.sort((a: any, b: any) => a.offers[0].fuel.name.toUpperCase().localCompare(b.offers[0].fuel.name))
When I console log the above it just return the data in the same order. I have set up a fiddle below to replicate the issue I am having.
Here is a fiddle
You are currently sorting the orders array based on the first item inside offers array. Instead, you should sort each object's offers array inside the orders
const orders=[{_id:"5d14a31490fb1e0012a3d2d8-1",orderId:"0JL5ORM0JT-1",created:"2019-06-27T11:05:56.377Z",createdDate:"2019-06-27T09:05:56.377Z",offers:[{price:95.27,fuel:{_id:"5ce13948eaef5200113b0de8",name:"Diesel B7",description:"Diesel",lpt:0,duty:0,type:"SPOT",created:"2019-05-19T11:08:56.417Z"}},{price:95.27,fuel:{_id:"5ce13948eaef5200113b0de8",name:"Petrol",description:"Petrol",lpt:0,duty:0,type:"SPOT",created:"2019-05-19T11:08:56.417Z"}},{price:95.27,fuel:{_id:"5ce13948eaef5200113b0de8",name:"Fossil Fuel",description:"Fossil Fuel",lpt:0,duty:0,type:"SPOT",created:"2019-05-19T11:08:56.417Z"},}]}];
orders.forEach(o =>
o.offers.sort((a, b) => a.fuel.name.localeCompare(b.fuel.name))
);
console.log(orders)

Updating MongoDB nested array using same path as the search query

I have the following problem, I want to update a document with a path id.metadata.panels.items where panels is an array and items is an array. My search query looks at the items and displays only those that match the criteria of metadata.panels.items.member.type: 'owner' - then I want to update the 'owner to 'account'.
When I am trying to update having the search path same as update path I get an error message saying: cannot use the part metadata.panels.items.member.type to traverse the element.
The documents have their own
How can I resolve this problem?
I have already tried to go through the collection using nested forEach statements to iterate through each of the arrays but I am not sure what to do next.
var records = db.getCollection('sample').find({"metadata.panels.items.member.type":"
[owner]"})
records.forEach(function(id) {
var newFields = [];
metadata.panels.forEach(function(panel, panelIndex){
panels.items.forEach(function (item, itemIndex) {
})
})
})
Sample document structure:
{
"panels": [{
"name": "categories",
"items": [{
"member": {
"type": "[Owner]",
"subtype": "[Contractor]"
},
"format": {
"members": {}
}
}]
},
{
"name": "localisation",
"items": [{
"member": {
"city": "NY",
"state":"NY"
}
}]
}]
}
Expected result:
{
"panels": [{
"name": "categories",
"items": [{
"member": {
"type": "[Account]",
"subtype": "[Contractor]"
},
"format": {
"members": {}
}
}]
},
{
"name": "localisation",
"items": [{
"member": {
"city": "NY",
"state":"NY"
}
}]
}]
}
I figured it out.
var newFields = [];
var records = db.getCollection('sample').find({"metadata.panels.items.member.type":"
[owner]"})
records.forEach(function(id) {
metadata.panels.forEach(function(panel, panelIndex){
panels.items.forEach(function (item, itemIndex) {
// I have generated update statements as strings
// first list is always position 0 and this goes to the statement
// second list get's populated from itemIndex
// added them to the newFields list
})
})
})
newFields.forEach(function(i){
eval(i)
})

How can I merge and match 2 separate objects?

What I want
I have 2 different Java-Script arrays/objects but with matching Ids. I want to merge them into a new object. So both the main object data and any matched elements from the secondary object are merged into a combined result.
What I tried
I tried using Object.assign() function but with no success.
Given Input
Example code, so I have 2 separate objects (main and lines):
let main = [
{
"Id": "1",
"Name": "Testing data"
}
]
let lines = [
{
"OtherId": "1",
"code": "AU-29830"
},
{
"OtherId": "1",
"code": "AU-29854-Single"
},
{
"OtherId": "1",
"code": "TV-BB21084623"
},
{
"OtherId": "2",
"code": "Don't Merge"
},
{
"OtherId": "3",
"code": "Don't Merge"
}
]
Expected Output
I want to merge those 2 arrays, so that the output should be a single array containing the merged main-object. This merged main-object should contain the original content of itself plus nested the filtered secondary array (only containing matching objects). The filtering was done using the id from the main array's object which has to match (the slightly deviating id) from each object of the secondary-array.
The resulting array should look like this:
let result = [
{
"Id": "1",
"Name": "Testing data",
"lines": [
{
"OtherId": "1",
"ProductCode": "AU-29830"
},
{
"OtherId": "1",
"ProductCode": "AU-29854-Single"
},
{
"OtherId": "1",
"ProductCode": "TV-BB21084623"
}
]
}
]
As your main is an array, I'm assuming you might end up with more than one main item in it. If so, here's one way to merge your line items onto each one:
const mergedMainItems =
main.map(mainItem=>({
...mainItem,
lines: lines.filter(line=>mainItem["Id"] === line["OtherId"])
}))
I think for this example this will work:
let result = [];
result.push({...main[0]}); //or even result.push(main[0])
result[0].lines = [];
for(let l in lines){
if(lines[l].code != "Don't Merge"){
result[0].lines.push({OtherId: lines[l].OtherId, ProductCode: lines[l].code})
}
}

Nested forEach issue

I have two arrays of object, the first array (printers, around 80 elements) is made of the following type of objects:
[{
printerBrand: 'Mutoh',
printerModel: 'VJ 1204G',
headsBrand: 'Epson',
headType: '',
compatibilty: [
'EDX',
'DT8',
'DT8-Pro',
'ECH',
],
cartridges: [],
},
....
]
The second array (cardridges, around 500 elements) is made of the following type of objects:
[
{
"customData": {
"brand": {
"value": {
"type": "string",
"content": "ECH"
},
"key": "brand"
},
"printer": {
"value": {
"type": "string",
"content": "c4280"
},
"key": "printer"
}
},
"name": "DT8 XLXL",
"image": {
"id": "zLaDHrgbarhFSnXAK",
"url": "https://xxxxxxx.net/images/xxxxxx.jpg"
},
"brandId": "xxxxx",
"companyId": "xxxx",
"createdAt": "2018-03-26T14:39:47.326Z",
"updatedAt": "2018-04-09T14:31:38.169Z",
"points": 60,
"id": "dq2Zezwm4nHr8FhEN"
},
...
]
What I want to do first is to is to iterate through the first array and and then iterate for all the cardridge available: if a the value customData.brand.value of a cardridge is included inside the array 'compatibility' of a printer, then I have to add this cardridge object inside the cardridges array of this printer. I have tried but somehow the iteration doesn't take place correctly. This is what I tried:
printers.forEach((printerItem) => {
const printer = printerItem;
printer.compatibilty.forEach((compatibilityItem) => {
const compatibility = compatibilityItem;
cardridges.forEach((cartridge) => {
if (compatibility === cartridge.customData.brand.value.content) {
printer.cartridges.push(cartridge);
}
});
});
});
What am I doing wrong?
You're accessing the wrong property. It should be cartridge.customData.brandName.value.content, carefully note brandName.value rather than brand.value
Your issue is that you're accessing it by the wrong property - brand and not brandName.
Furthermore, if you're targeting everything but IE, you could simplify your nested for loops to utilize some fancy ES6 array methods.
printers.forEach((p) => {
p.cartridges.push(cartridges.filter((c) => {
const brandName = c.customData.brandName.value.content;
return p.compatibilty.includes(brandName);
}));
});

Categories