Filter object array via nodejs - javascript

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));

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.

Merge a Product Config JSON with Generic Config JSON- Issue While Merging Arrays inside it

I have 2 different Json files
1: a Deaflut JSON file
2: A Product Based JSON file
I need to merge them together in such a way that if a feature in default is not in a product that needs to be added to product config from default one.
for this merge, I used "lodash.mergewith" https://www.npmjs.com/package/lodash.mergewith.
so this is now taking care of the merge, But the file contains multiple nested JSON arrays inside it.
to handle that there is an option to use a customizer method that can handle array merge as mentioned in the usage of lodash.mergewith. I need a customizer that can find the Label from Deaflut and compare it with the Product if the Product has the same Label value then replace the URL with the Product URL. else if the Label is not in Product config, then use it from default as it is.
Example
Default config.json:-links is an array of this json with path : object►login►options►sections►2►links
"links": [{
"url": "www.google.com",
"label": "Lable1"
},
{
"url": "www.google.com",
"label": "Label2"
},
{
"url": "www.google.com",
"label": "Label3"
},
{
"url": "www.google.com",
"label": "Label4"
}
]
Productconfig.json:- links is an array inside this of the path: object►login►options►sections►2►links
"links": [{
"url": "www.product1.com",
"label": "label1"
},
{
"url": "www.product2.com",
"label": "Label2"
}
]
** after merge mergedconfig.json "Links" need to be like this.**
"links": [{
"url": "www.product1.com",
"label": "Label1"
},
{
"url": "www.product2.com",
"label": "Label2"
},
{
"url": "www.google.com",
"label": "Label3"
},
{
"url": "www.google.com",
"label": "Label4"
}
]
The main concern is this Array is coming inside a JSON file inside some JSON objects
like eg if the Array is inside links[] it will be in a path like : object►login►options►sections►2►links[]. and this Links Array similarly present inside in some other paths eg: object►register►options►sections►2►links[]
So I need to figure out all the Array like this and for each of the Arrays, I need to perform this action.
Just use Array.map and Array.find:
let links= [
{
"url": "www.google.com",
"label": "Label1"
},
{
"url": "www.google.com",
"label": "Label2"
},
{
"url": "www.google.com",
"label": "Label3"
},
{
"url": "www.google.com",
"label": "Label4"
}
];
let plinks= [{
"url": "www.product1.com",
"label": "label1"
},
{
"url": "www.product2.com",
"label": "Label2"
}
];
let results = links.map(lnk=>{
plnk = plinks.find(pl=>pl.label.toLowerCase()===lnk.label.toLowerCase());
return plnk || lnk
});
console.log(results);
for clean access to nested JSON keys you can use ES like this:
let a = {
b: {
c: [1,2,3]
}
};
let {c} = a?.b;
console.log(c);

How to get specific array from JSON object with Javascript?

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.

Searching through JSON object

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/

basic java script json child array decoding

I have been teaching myself some basic javascript the last couple of days and playing with google scripting as well as the twitter api and have come a bit unstuck on something that should probably be quite easy!
For sake of easierness of typing so my return from twitter api looks like this
[id:1
connections: "NONE"
],
[id:2
connections: ["following", "followed_by"]
]
What I am trying to do is find out out if the key 'following' exists for user 2, but I am really struggling!
The twitter api docs show an examples json as
[
{
"name": "Taylor Singletary",
"id_str": "819797",
"id": 819797,
"connections": [
"none"
],
"screen_name": "episod"
},
{
"name": "Twitter API",
"id_str": "6253282",
"id": 6253282,
"connections": [
"following",
"followed_by"
],
"screen_name": "twitterapi"
}
]
Can any point me in the correct direction?, how do I find out if following exists?
Thanks
connections: ["following", "followed_by"] is an array. To check if an array contains a special value you can use indexOf():
var a = [1, 2, "three", 44];
a.indexOf(1); // 0
a.indexOf(2); // 1
a.indexOf("three"); // 2
a.indexOf(22); // -1
So to check if "following" is in the array:
if (connections.indexOf("following") !== -1) {
// yeah!
} else {
// doh!
}
To count the objects in your example which have "following":
var o = [
{
"name": "Taylor Singletary",
"id_str": "819797",
"id": 819797,
"connections": [
"none"
],
"screen_name": "episod"
},
{
"name": "Twitter API",
"id_str": "6253282",
"id": 6253282,
"connections": [
"following",
"followed_by"
],
"screen_name": "twitterapi"
}
];
var withFollowing = o.filter(
function (i) {
return i.connections.indexOf("following") !== -1;
}
);
// filter() returns a new array
// this new array has only the elements for which the function returns true
console.log(withFollowing.lenght);

Categories