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/
Related
[
{
"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.
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>
I am working with facebook JS SDK which returns user's information in JSON format. I know how to get the response like response.email which returns email address. But how to get an element from a nested array object? Example: user's education history may contain multiple arrays and each array will have an element such as "name" of "school". I want to get the element from the last array of an object.
This is a sample JSON I got:-
"education": [
{
"school": {
"id": "162285817180560",
"name": "Jhenaidah** School"
},
"type": "H**hool",
"year": {
"id": "14404**5610606",
"name": "2011"
},
"id": "855**14449421"
},
{
"concentration": [
{
"id": "15158**968",
"name": "Sof**ering"
},
{
"id": "20179020**7859",
"name": "Dig**ty"
}
],
"school": {
"id": "10827**27428",
"name": "Univer**g"
},
"type": "College",
"id": "9885**826013"
},
{
"concentration": [
{
"id": "108196**810",
"name": "Science"
}
],
"school": {
"id": "2772**996993",
"name": "some COLLEGE NAME I WANT TO GET"
},
"type": "College",
"year": {
"id": "1388*****",
"name": "2013"
},
"id": "8811215**16"
}]
Let's say I want to get "name": "some COLLEGE NAME I WANT TO GET" from the last array. How to do that with Javascript? I hope I could explain my problem. Thank you
Here is a JsFiddle Example
var json = '{}' // your data;
// convert to javascript object:
var obj = JSON.parse(json);
// get last item in array:
var last = obj.education[obj.education.length - 1].school.name;
// result: some COLLEGE NAME I WANT TO GET
If your json above was saved to an object called json, you could access the school name "some COLLEGE NAME I WANT TO GET" with the following:
json.education[2].school.name
If you know where that element is, then you can just select it as already mentioned by calling
var obj = FACEBOOK_ACTION;
obj.education[2].school.name
If you want to select specifically the last element, then use something like this:
obj.education[ obj.education.length - 1 ].scool.name
Try this,
if (myData.hasOwnProperty('merchant_id')) {
// do something here
}
where JSON myData is:
{
amount: "10.00",
email: "someone#example.com",
merchant_id: "123",
mobile_no: "9874563210",
order_id: "123456",
passkey: "1234"
}
This is a simple example for your understanding. In your scenario of nested objects, loop over your JSON data and use hasOwnProperty to check if key name exists.
I have an object array which look something like below,
{
"data": [
{
"name": "HTML",
"description": "Hyper Text Markup Language"
},
{
"name": "CSS",
"description": "Cascading Style Sheet"
},
{
"name": "JS",
"description": "Javascript"
}
]
}
I get the above object array as a response from this end point /get/technologies, suppose if this end point is gonna have a query string some thing like this /get/technologies?q=CSS how can i filter the response just to render the below,
{
"data": [
{
"name": "CSS",
"description": "Cascading Style Sheet"
}
]
}
I have a node/express app so in the controller if i do "req.query.q" then i can grab the query parameter, with that query parameter how can i filter the original object array.. i came across some npm packages but not sure which would suite my need,
https://www.npmjs.com/package/filter-array
https://www.npmjs.com/package/object-filter
https://www.npmjs.com/package/array-filter
https://www.npmjs.com/package/array-query
It would also be nice if i can grab the query parameter and find the matching texts.. say for example if the query parameter is just "SS" then the result should render both CSS and JS since the text "S" is there in both of them.
Working Example
Try this:
var d = [
{
"name": "HTML",
"description": "Hyper Text Markup Language"
},
{
"name": "CSS",
"description": "Cascading Style Sheet"
},
{
"name": "JS",
"description": "Javascript"
}
];
var a = d.filter(function(el) {
return el.name === 'CSS';
});
You could just use filter:
var data = [
// the array to be filtered
];
var filteredArray = data.filter(item => (item.name === req.query.q));
I seem to be having difficulty in grasping how to drill down to get to nested JSON and display it on a page using angular. For example I have the following JSON structure and I want to display the connectivity products under portfolio in an ng-repeat...
{
"addons": [
...
],
"attributes": [
...
],
"portfolios": [
{
"connectivity": [
{
"product-1": {
"label": "product-1",
"description": "Description in here"
}
},
{
"product-2": {
"label": "product-2",
"description": "Description in here"
}
}
]
}
]
}
So far I have tried it two different ways.
$scope.listOfProducts = allProducts.data.portfolios.connectivity;
and in the ng-repeat
ng-repeat='product in listOfProducts.portfolios.connectivity'
What would be the correct way to loop through and display the 'connectivity' products in a ng-repeat? Thanks
EDIT:
I've changed the JSON to this structure...
{
"addons": [
...
],
"attributes": [
...
],
"portfolios": [
{
"connectivity": [
{
"label": "product-1",
"description": "Description in here"
},
{
"label": "product-2",
"description": "Description in here"
}
]
}
]
But I still can't seem to get ng-repeat to display the products in connectivity.
$scope.listOfProducts = allProducts.data.portfolios.connectivity
Since listOfProducts is already set to the connectivity array, you would just ng-repeat="product in listOfProducts"
<div ng-repeat="product in listOfProducts">
{{product.label}}
</div>
Edit: Well, your array is sort of irregular, since you're creating a property called product-[index] for each item. Do you have control of the data which is returned? Your array should just have the objects, like:
"connectivity": [
{
"label": "product-1",
"description": "Description in here"
},
{
"label": "product-2",
"description": "Description in here"
}
]