compare and delete json data using javascript - javascript

Below is my json code:
{
"uID": "4564646",
"favorites": [
{ "name" : "my store",
"id" : "87654321",
"items":
[
{
"productID": "46565",
"title": "Project",
"type": "Weekend Project"
},
{
"productID": "112",
"title": "Bathroom",
"type": "Weekend Project"
},
{
"productID": "785",
"title": "link",
"type": "main Project"
}
]
}
]
}
Now i want to check the PRODUCTID for each and delete the entry from items which matches my product id 112 .
I want to use javascript only, the array items is not fixed and also Do i have to parse the json before applying the deletion method.

var obj = JSON.parse(json_string);
var fav_items = obj.favorites[0].items;
for (var i = fav_items.length - 1; i >= 0; i--) {
if (fav_items[i].productID == 112) {
fav_items.splice(i, 1);
}
}
Note that you need to do the loop backwards, because when you splice out an element from the array, all the elements after it get there indexes shifted down. If you do a normal upward loop, you'll skip over the elements after the ones you delete.

Just do:
for (var i = 0; i < data.favorites[0].items.length; i++) {
if (data.favorites[0].items[i].productID != 112) {
data.favorites[0].items.splice(i, 1);
i--; //DONT FORGET THIS
}
}
splice can remove array elements - dont forget the i-- though when splicing in a loop as the array has the potential to shorten with each iteration.

Related

Iterate through array of objects,not giving required output

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

Array of JavaScript objects from JSON

I have a deeply nested JSON structure as below:
[
{
"ATA": "49",
"Description": "APU",
"MSI": "",
"Level":"1",
"ChildNodes": {
"Nodes": [
{
"ATA": "49-10",
"Description": "Power Plant",
"MSI": "",
"Level":"2",
"ChildNodes": {
"Nodes": [
{
"ATA": "49-13",
"Description": "APU Mounts",
"MSI": "Yes",
"Level":"3",
"ChildNodes": {
"Nodes": [
{
"ATA": "49-13-01",
"Description": "APU Gearbox Mount Bracket",
"MSI": "Yes",
"Level":"4"
}]
}
}
]
}
}
]
}
}
]
I'm trying to convert the following into an array of the form for easier processing of this data to show in a tabular format:
[{ATA:"49",Description:"APU",MSI:""},{ATA:"49-10",Description:"PowerPlant",MSI:""}]...
I've tried a lot of ways and though I can get all the key / value pairs, I can't figure out how to do this. I can't change the JSON since all the child nodes have dependencies. Any ideas?
Edit: I tried the following solution to get all key / value pairs: Traverse all the Nodes of a JSON Object Tree with JavaScript but I can't find out when to start a new object.
You should use a recursive function for this:
function processNodes(nodes, output){
for (var i = 0, l = nodes.length; i < l; ++i){
output.push({
"ATA": nodes[i]["ATA"],
"Description": nodes[i]["Description"],
"MSI": nodes[i]["MSI"]
});
if (nodes[i]["ChildNodes"]){
processNodes(nodes[i]["ChildNodes"]["Nodes"], output);
}
}
}
Then:
var json = JSON.parse( ... );
var output = [];
processNodes(json, output);
console.log(output);

How can I do a multidimensional search with JSON in Javascript?

I am trying to write a basic, experimental search system using JavaScript and JSON, with the searchable data contained in the JSON file. Multiple 'posts' are listed in the file, and each post has an array of 'tags'. My intent is to search through each posts tags, and retrieve only the posts that have tags matching a query, such as "funny cat video" (the posts would have to have all three tags, "funny", "cat", and "video", to be returned).
My particular concern is performance. I am sure that this technique will be inefficient, as there are approximately 2000 posts, and each one has from 5 to 50 tags, but it has to be done with JavaScript. I am already referencing from this website on how to maximise performance, though I could do with some extra help.
Here is my code so far for storing the data:
{
"index": {
"count": "2",
"posts": [
{
"id": "1",
"date": "2014-11-21 17:16:39 GMT",
"url": "http://url/",
"image": "http://big_image/",
"thumbnail": "http://little_image/",
"tags": ["funny", "cat", "picture", "falling", "chair", "window sill", "funny"]
},
{
"id": "2",
"date": "2014-11-20 17:57:32 GMT",
"url": "http://url1/",
"image": "http://big_image1/",
"thumbnail": "http://little_image1/",
"tags": ["funny", "cat", "picture", "jumping", "water", "bath", "funny"]
}
]
}
}
And this is my Javascript:
var query = "funny cat bath".split(" ");
var data = JSON.parse("THE JSON GOES HERE");
var count = data.index.count;
var index = data.index.posts;
for (var i = 0, indexLength = index.length; i < indexLength; i++) {
tags = index[i].tags;
for (var q = 0, queryLength = query.length; q < queryLength; q++) {
if(tags.indexOf(query[q]) !== false) {
console.log(index[i]);
}
}
}
Unfortunately, I can't figure out how to get it to return only the posts that have all three tags, and it returns all posts with any of the tags supplied. Not only that, but it returns duplicates.
Does anybody have a better solution? I'm stuck.
You need to use a flag and only "write" out the match when they are all found, you are writing it out when one is found. Plus indexOf returns -1, not false. Basic idea below:
var data = {
"index": {
"count": "2",
"posts": [
{
"id": "1",
"date": "2014-11-21 17:16:39 GMT",
"url": "http://url/",
"image": "http://big_image/",
"thumbnail": "http://little_image/",
"tags": ["funny", "cat", "picture", "falling", "chair", "window sill", "funny"]
},
{
"id": "2",
"date": "2014-11-20 17:57:32 GMT",
"url": "http://url1/",
"image": "http://big_image1/",
"thumbnail": "http://little_image1/",
"tags": ["funny", "cat", "picture", "jumping", "water", "bath", "funny"]
}
]
}
};
var query = "funny cat bath".split(" ");
var filteredSet = []; //where the matched objects will reside
var posts = data.index.posts; //get the posts
for (var i=0; i<posts.length;i++) { //loop through the posts
var post = posts[i];
var tags = post.tags; //reference the tags
var hasMatch = true; //flag to hold the state if we have a good match - set to true by default
for (var j=0; j<query.length; j++) { //loop through the tags the user is looking for
var index = tags.indexOf(query[j]); //look for it in the set [Note older IEs needs polyfill see MDN for code]
if (index===-1) { //indexOf returns -1 if not found
hasMatch=false; //set Boolean flag so we do not record item
break; //exit loop - no reason to keep checking
}
}
if (hasMatch) { //if we found all the tags
filteredSet.push(post); // add to the filtered set
}
}
console.log(filteredSet); //show the filtered set

Getting first item in jsonp object

I'm working with a jsonp object, it lists items like this:
{
"played_tracks": [
{
"artist": {
"id": 5524,
"name": "BAAUER",
}
},
"title": "Harlem Shake",
},
{
"artist": {
"id": 114,
"name": "BIRDY",
}
},
"title": "Wings ",
},
{
"artist": {
"id": 1257,
"name": "MILEY CYRUS",
}
},
"title": "Wrecking Ball",
},
{
etc........
Now currently I'm using this code to loop through all of them:
for(i in json.played_tracks)
{
oTrack = json.played_tracks[i];
etc.........
}
How do I adjust my code to only display the last played song? The last song is the first item in the jSONP object.
Instead of looping over json.playedTracks, just fetch the first item of the array like so:
oTrack = json.playedTracks[0];
As you say, the first item is the "last played track," so that should do what you want. If you need the other end of the list though, you can grab that element just as easily:
oTrack = json.playedTracks[json.playedTracks.length - 1];

problem parsing JSON Strings

var records = JSON.parse(JsonString);
for(var x=0;x<records.result.length;x++)
{
var record = records.result[x];
ht_text+="<b><p>"+(x+1)+" "
+record.EMPID+" "
+record.LOCNAME+" "
+record.DEPTNAME+" "
+record.CUSTNAME
+"<br/><br/><div class='slide'>"
+record.REPORT
+"</div></p></b><br/>";
}
The above code works fine when the JsonString contains an array of entities but fails for single entity. result is not identified as an array!
Whats wrong with it?
http://pastebin.com/hgyWw5hd
result is not an array. Do you see any square brackets in your JSON? no you do not. it does not contain any arrays.
{
"result": {
"ID": "30",
"EMPID": "1210308550",
"CUSTID": "1003",
"STATUS": "2",
"DATEREPORTED": "1273234502",
"REPORT": "this is one more report!",
"NAME": "Sandeep Savarla",
"CUSTNAME": "Collateral",
"LOCID": "4",
"LOCNAME": "Vijayawada",
"DEPTNAME": "SALES"
}
}
Can you show me what your "valid" json looks like when the function above works?
Just make sure it's an array before you iterate
if ( 'undefined' == typeof records.result.length )
{
records.result = [records.result];
}
Your code is looping through records.result as if it were an array.
Since it isn't an array, your code does not work.
This simplest solution is to force it into an array, like this:
var array = 'length' in records.result ? records.result : [ records.result ];
for(var x = 0; x < array.length; x++) {
var record = array[x];
...
In your code result is an object, not an array. Wrap it's value in square brackets to make it an array:
{
"result": [{
"ID": "30",
"EMPID": "1210308550",
"CUSTID": "1003",
"STATUS": "2",
"DATEREPORTED": "1273234502",
"REPORT": "this is one more report!",
"NAME": "Sandeep Savarla",
"CUSTNAME": "Collateral",
"LOCID": "4",
"LOCNAME": "Vijayawada",
"DEPTNAME": "SALES"
}]
}

Categories