I have a json collection stored as {"books": [{...}, ... ]} in a file. "books" is a list of json objects where each is a book. For example:
{
"books": [
{
"items": [
{
"id": "jD8iswEACAAJ",
"volumeInfo": {
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0984782850"
},
{
"type": "ISBN_13",
"identifier": "9780984782857"
}
],
},
}
]
},
]
}
I have a need to read the json using _.where, specifically search every item in the collection for the "identifier" value of "type": "ISBN_10". Then return the full json object aka {"items": [...]}.
Suppose req.params.id is the "identifier" value (i.e. 0984782850).
This piece of code is not working
var _ = require('underscore');
...
app.get('/api/books/:id', function(req, res) {
var book = _.where(booksData.books.items[0].volumeInfo.industryIdentifiers[0], {identifier: req.params.id});
res.json(book);
});
it is returning
TypeError: Cannot read property '0' of undefined at position 43
The file has valid json, I have tried
var book = _.where(booksData.books, {items[0].volumeInfo.industryIdentifiers[0].identifier: req.params.id});
which also does not work
There is always one item in "items" and the ISBN_10 identifier is the first item in "industryIdentifiers" hence items[0].volumeInfo.industryIdentifiers[0].identifier
What am I doing wrong?
*EDIT: I tried with industryIdentifiers, but response is [ ]
Don't use industryIdentifiers[1]. You want to search the entire industryIdentifiers array, not a single object.
var book = _.where(booksData.books[0].items[0].volumeInfo.industryIdentifiers, {identifier: req.params.id})[0];
You also need books[0], since books is also an array.
const booksData = {
"books": [
{
"items": [
{
"id": "jD8iswEACAAJ",
"volumeInfo": {
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "0984782850"
},
{
"type": "ISBN_13",
"identifier": "9780984782857"
}
],
},
}
]
},
]
};
var book = _.where(booksData.books[0].items[0].volumeInfo.industryIdentifiers, {identifier: "0984782850"})[0];
console.log(book);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
Related
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
})
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)
})
I'm trying to write a node.js script to create a set of Facebook audiences based on URL structure, but I'm getting the below error and I can't seem to identify what is wrong with the JSON I'm sending:
Error I'm getting back: FacebookRequestError: Invalid rule JSON format: Invalid rule JSON format.
It seems that the 'rule' property of the 'params' object is somehow invalid, but I can't identify what is wrong with it. I even tried copying their example from the docs and it gave the same error. I also pasted the JSON into the API explorer and the editor there indicated valid JSON, but the API response was the same.
api explorer screenshot
After reading this similar question, I tried a bunch of variations using single vs double-quotes, JSON.stringifying the whole thing, part of it, none of it, etc... I'm hoping fresh eyes might catch it.
My Code:
"use strict";
const bizSdk = require("facebook-nodejs-business-sdk");
const AdAccount = bizSdk.AdAccount;
const CustomAudience = bizSdk.CustomAudience;
const access_token = "REDACTED";
const app_secret = "REDACTED";
const app_id = "REDACTED";
const id = "act_REDACTED";
const pixelID = "REDACTED";
const api = bizSdk.FacebookAdsApi.init(access_token);
const showDebugingInfo = true; // Setting this to true shows more debugging info.
if (showDebugingInfo) {
api.setDebug(true);
}
const logApiCallResult = (apiCallName, data) => {
console.log(apiCallName);
if (showDebugingInfo) {
console.log("Data:" + JSON.stringify(data));
}
};
let fields, params;
fields = [
];
params = {
"name": "Website - Viewed Product - Corrugated Containers - 180 days",
"rule": {
"inclusions": {
"operator": "or",
"rules": {
"inclusions": {
"operator": "or",
"rules": [
{
"event_sources": [
{
"id": pixelID,
"type": "pixel"
}
],
"retention_seconds": 8400,
"filter": {
"operator": "and",
"filters": [
{
"field": "url",
"operator": "i_contains",
"value": "/products/corrugated-containers"
}
]
}
}
]
}
}
}
},
"retention_days": "180",
"prefill": "1"
};
const customaudiences = (new AdAccount(id)).createCustomAudience(
fields,
params
);
logApiCallResult("customaudiences api call complete.", customaudiences);
It looks like I had accidentally nested a rules object within a rules object somehow! I fixed that and it created the audience without throwing an error...now I can't see the audience definition in Facebook's interface to check that it's correct, but that's a completely different topic.
I changed...
params = {
"name": "Website - Viewed Product - Corrugated Containers - 180 days",
"rule": {
"inclusions": {
"operator": "or",
"rules": {
"inclusions": {
"operator": "or",
"rules": [
{
"event_sources": [
{
"id": pixelID,
"type": "pixel"
}
],
"retention_seconds": 8400,
"filter": {
"operator": "and",
"filters": [
{
"field": "url",
"operator": "i_contains",
"value": "/products/corrugated-containers"
}
]
}
}
]
}
}
}
},
"retention_days": "180",
"prefill": "1"
};
to
params = {
"name": "Website - Viewed Product - Corrugated Containers - 180 days",
"rule": {
'inclusions': {
'operator': 'or',
'rules': [{
'event_sources': [{
'id': pixelID,
'type': 'pixel'
}],
'retention_seconds': retention_seconds,
'filter': {
'operator': 'and',
'filters': [{
'field': 'url',
'operator': 'i_contains',
'value': '/products/corrugated-containers'
}]
}
}]
}
},
"retention_days": retention_days,
"prefill": "1"
};
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);
}));
});
I am trying to search through a json object to select some values. For example I have a variable with the value 'product-2' and I want to look through the json object and return the attributes array of 'product-2'
{
"attributes": [
...
],
"portfolio": [
{
"conn": [
{
"product": "product-1",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
},
{
"product": "product-2",
"description": "Description in here"
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
}
]
}
]
Could anyone tell me how I can achieve this? Thank you
EDIT:
As per Pramods request - I was working with the following js (although its really wrong I am sure)
$scope.productAttributes = [];
$scope.getProductDetails = function (product_id) {
console.log(product_id);
//search trough json
angular.forEach($scope.listOfProducts.product_id, function(value, key) {
// I was thinking I could loop through the json and when I find the matching product, then push its attributes into an array?
// if (key === enteredValue) {
// $scope.productAttributes.push({atribute: key});
// }
});
};
EDIT No.2
The JSON structure has changed
Use a filter to destructure the array.
In my example I use a filter within a Controller. This should probably be done in a service or a view. For brevity I used the filter in a controller.
The filter expression essentially says, return the first object in the array with a property 'product' that is 'product-2'
var app = angular.module('app', []).controller('MyController', MyController);
MyController.$inject = ['$filter'];
function MyController($filter) {
var data = [
{
"product": "product-1",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
},
{
"product": "product-2",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
}
]
this.product = $filter('filter')(data, {product: "product-2"})[0];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="MyController as vm">
Product-2: {{vm.product}}
</div>
</div>
Well, if you don't know how product-2 will be nested and you actually need to search for it, then you need to do a recursive search. A recursive function is a function that calls itself.
This means that you iterate over each of the keys, and if the key is an object, call the recursive function on that key as well, until the key you want is found.
Here is a similar question, with a few algorithms provided for doing recursive search on a JSON structure in JavaScript: traversing through JSON string to inner levels using recursive function
I think your JSON is wrong , So please correct it
Correct JSON
{
"attributes": [],
"portfolio": [
{
"conn": [
{
"product-1": {
"label": "product-1",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
}
},
{
"product-2": {
"label": "product-2",
"description": "Description in here",
"attributes": [
"OriginPostcode",
"Size",
"Bandwidth"
],
}
}
]
}
]
}
And to parse above json and return product information following is the code
$(document).ready(function() {
$.each(dict['portfolio'][0], function(key, list){
$.each(list, function(index, value){
$.each(value, function(product, info){
if (product == "product-2"){
answer = {}
answer[product] = info;
return JSON.stringify(answer);
}
});
});
});
});
Fiddle link :-
http://fiddle.jshell.net/2t8uknkc/