Using JavaScript to search JSON objects based on key value pairs

Consider a scenario where you have an array of objects in users.json:

{"key":"userSubscriptions","value":
[{"channel":"Netflix","user":"Bobby","region":"NA"},
[{"channel":"Netflix","user":"Bobby","region":"EU"},
[{"channel":"Netflix","user":"Jamie","region":"SEA"},
[{"channel":"Prime Video","user":"Bobby","region":"NA"}]}

If we want to filter this data such that the final result will be

console.log(result); // Bobby, your region subscriptions are: Netflix: (NA, EU), Prime Video: (NA)

Your help on achieving this outcome would be greatly appreciated!

UPDATE: I attempted using methods like .filter() and .map(), but unfortunately haven't had success yet.

Answer №1

To effectively organize and display data, utilize lodash for grouping and mapping.

var details = {
                "key":"userSubscriptions",
                "value":
                [{"channel":"Netflix","user":"Bobby","region":"NA"},
                {"channel":"Netflix","user":"Bobby","region":"EU"},
                {"channel":"Netflix","user":"Jamie","region":"SEA"},
                {"channel":"Prime Video","user":"Bobby","region":"NA"}]
            }

            var usersData = _.chain(details.value)
                .groupBy("user").map((data, role) => ({ user: role, info: data })).value();

                usersData.forEach(item => {
                    console.log(item)

                    console.log(`${item.user}, your current region subscriptions include: Netflix: ${item.info.map(i=>i.channel).join(',')}, Prime Video: ${item.info.map(i=>i.region).join(',')}`)
                });

Answer №2

There seems to be an issue with your JSON data. However, I have made adjustments to align it with your intended structure.

This new structure organizes the data by user and includes a function that can display the Subscriptions and Regions for any specified user.

const jsonString = `{"key":"userSubscriptions","value":[{"channel":"Netflix","user":"Bobby","region":"NA"},{"channel":"Netflix","user":"Bobby","region":"EU"},{"channel":"Netflix","user":"Jamie","region":"SEA"},{"channel":"Prime Video","user":"Bobby","region":"NA"}]}`;

const obj = JSON.parse(jsonString);                                  // Parsing the string into an object

const byUser = obj.value.reduce((acc, o) => {                        // Reducing the array values into one object
  if (!acc[o.user]) acc[o.user] = {};                                // Creating user property in accumulator if not already present
  if (acc[o.user][o.channel]) acc[o.user][o.channel].push(o.region); // Adding region to existing channel array
  else acc[o.user][o.channel] = [o.region];                          // Creating new channel array with region
  return acc;                                                        // Returning modified object for next iteration
}, {});

function printForUser(userName) {                                    // Function to print subscriptions and regions for a given user
  const user = byUser[userName];                                     // Getting the user object from byUser
  return Object.keys(user).reduce((acc, k) => {                      // Reducing keys of user object to form a string
    return acc + ` ${k}: (${user[k].join(", ")}),`;                  // Combining subscription and regions information
  }, `${userName}, your region subscriptions are:`).slice(0, -1);    // Initializing string and removing last comma
}

console.log( printForUser("Bobby") );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can VueJS 1 and 2 be integrated within the same package.json configuration?

At the moment, my JavaScript files are using VueJS 1. However, I am preparing to work on a new section of the system and want to switch to VueJS 2. ...

Unable to access Vue.js cookies: they are not defined

I integrated vue-cookies into my project successfully. In the main.js file, I added the following code: createApp(App) .use(store) .use(router, axios, VueCookies) The script section in App.vue file looks like this: <script> import Navbar fr ...

What is the minimum number of lines that can be used for javascript code?

Currently, I am in the process of developing a custom JavaScript minifier. One question that has come up is whether it is necessary to insert line breaks after a certain number of characters on a single line, or if it even makes a difference at all? For i ...

Working with attributes in AngularJS directives

Building an overlay (or modal window) in AngularJS has been on my mind, and I've made some progress with the html/css layout. Here's a sneak peek at what it looks like: <section class="calendar"> <a open-overlay="overlay-new-calenda ...

Updating a component (`AddBudgetModal`) while rendering a different component (`App`) is not possible. To identify the incorrect setState() call within the `AddBudgetModal` component

Here is the code snippet from App.jsx I'm facing an issue on line 44 where I'm attempting to open an addbudgetmodal by passing true or false. However, I'm getting an error message that says "Cannot update a component (App) while rendering a ...

Troubleshooting the issue of data retrieval failure in asp.net mvc controller using jquery.post()

I am currently working on an ASP.NET MVC web application that is written in VB.NET. My goal is to send data using jQuery to my controller. Below is the code for my controller: <HttpPost()> Function GetData(p As DataManager) As JsonResult ...

Emphasize a specific line of text within a <div> with a highlighting effect

I'm looking to achieve a similar effect as demonstrated in this fiddle As per StackOverflow guidelines, I understand that when linking to jsfiddle.net, it's required to provide some code. Below is the main function from the mentioned link, but f ...

Providing UI field attributes within server JSON data

Suppose I have numerous form fields that need to be displayed on the user interface. Additionally, in a standard Modify workflow, let's assume that these fields will have various attributes like value, mandatory, editable, disabled, label, regex (for ...

The plugin 'vue' specified in the 'package.json' file could not be loaded successfully

There seems to be an issue with loading the 'vue' plugin declared in 'package.json': The package subpath './lib/rules/array-bracket-spacing' is not defined by the "exports" in C:\Users\<my_username>\Folder ...

Issues arise with the functionality of Datatables when attempting to implement a

I am trying to sort the "Date Created" column in my table in descending order of the latest date. I found a forum that suggested using the datetime datatable sorting plugin, but it didn't work as expected. Can someone help me solve this issue? Below a ...

Another option instead of using $index for displaying serial numbers in ng-repeat

Looking to display a serial number for each table data entry being generated through the use of ng-repeat. The current code I have is as follows: <tr ng-repeat="usageRecord in applicationUsageDataForReport"> <td style="text-align: center">&l ...

Exploring the dynamics of parent and child components in Angular

I'm currently working on an Angular2 project and I've hit a roadblock with the parent/child component interaction. My goal is to have a "Producer" entity that can have multiple "Products". Ultimately, I aim to retrieve lists of products associat ...

Struggling to transfer information between POST and GET requests in Node/Express

Just diving into node/express, currently developing a weather application that receives location data from a form submission <form method="POST" action="/"> <input id="input" type="text" name="city" placeholder="Search by city or zip code" /> ...

Execute two tasks simultaneously in two separate workers utilizing the cluster module in node.js

I'm currently diving into clustering with NodeJS. My goal is to have two separate tasks - one handling node-sass and the other managing uglifyjs - each running on a distinct worker using cluster in NodeJS. The code I've implemented seems to be fu ...

Keep the multiselect dropdown list of the select component open

I am currently utilizing the Select component from material-ui-next. Overall, it functions quite smoothly. One scenario where I implement it is within a cell element of an Ag-Grid. Specifically, in this use case, I am making use of the multiselect feature ...

I want to search through an array of tuples to find a specific value in the first index, and if there is a match, I need to return the value in the second index of the matching tuple

I am dealing with an array of tuples: var tuparray: [string, number][]; tuparray = [["0x123", 11], ["0x456", 7], ["0x789", 6]]; const addressmatch = tuparray.includes(manualAddress); In my function, I aim to verify if the t ...

Update object properties in Angular controller dynamically

Take a look at my simple plunker Within the code, I am attempting to link a scope variable to an object property. $scope.name = 'World'; var obj = { "name":$scope.name } $scope.$watch('name', function(){ console.log(obj["name"]); ...

Mastering the art of transferring render :json => data to d3.js

I want to display the output of a JSON file as a d3.js graph, but I'm having trouble accessing the JSON data in my controller. Here is the relevant code: First, let's take a look at the model: class User < ActiveRecord::Base has_many :relat ...

Divide an HTML file into separate documents upon submitting a form

Is there a way to input HTML into a text area, then upon submission, have the system read the file, identify the class selector, and separate the HTML into multiple files saved in a directory? If you have any thoughts on how this could be accomplished, pl ...

Tips for resolving conflicts with jQuery on an ASP.NET webpage

On this page, I am using references and scripts for a date time picker and color box. However, only one of them works at a time - commenting out one script allows the other to work. I have tried using jQuery noconflict, but it did not resolve the issue. H ...