How to dynamically create an object with a key and a value as a list in AngularJS

Hello, I have an object with the following structure: [{name: 'abc', country : 'US'},{name: 'xyz', country : 'IN'},{name: 'mno', country : 'US'},{name: 'pqr', country : 'IN'}]

I am looking to convert this object into

{ US : [abc,mno], IN: [xyz,pqr] } using angular js. Can someone assist me in achieving this?

Answer №1

Utilize the Array.reduce() method to transform an array of objects into a new object based on the array data.

const input = [
    {name: 'abc', country : 'US'},
    {name: 'xyz', country : 'IN'},
    {name: 'mno', country : 'US'},
    {name: 'pqr', country : 'IN'}
];

// Implement reduce to iterate over each element and create a new object
const output = input.reduce(function(accumulator, element) {
  // Check if there is a record for this country
  if (!accumulator[element.country]) {
    // If not, create an array with only this name as the element
    accumulator[element.country] = [element.name];
  } else {
    // If it already exists, add the new value to the array
    accumulator[element.country].push(element.name);
  }
  // Return the updated object
  return accumulator;
}, {}); // <- initial value

The variable output will yield:

{
  "US": [
    "abc",
    "mno"
  ],
  "IN": [
    "xyz",
    "pqr"
  ]
}

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

How can one view all the static variables and methods associated with a class in Typescript or ES6?

Is it possible to retrieve all static variable names and static method names associated with a class, similar to how the Object.keys method returns a list of key names attached to an object? Typescript Example: class FindStatics { static num1:string = ...

Preserve the JavaScript Promise for later utilization

While experimenting with Node.js to construct the server side RESTApi, I encountered a situation where it functioned effectively during my independent tests. However, once deployed in a live environment, issues related to overflow arose. Specifically, when ...

AngularJS: Importing a parent directive within a child directive

Take a look at this Plunk example to understand better. I'm attempting to create a test scenario for accessing complex directives, but I encounter an error when trying to call a method from the parent directive: Parent Directive app.directive(&apos ...

Discovering every element on a webpage

Searching for elements in a webpage can be done using different methods. document.getElementsByTagName('*') and document.all Are there any other more efficient ways or are these two the most recommended? I am currently working on an element se ...

When the click event occurs, add a class. After a delay using a timeout function, remove the added

I am currently using Jimdo and I have a section where I can edit all the codes, which is working fine except for one feature. Any assistance would be greatly appreciated! Here is the code that adds a class to an animated SVG image with its status set as d ...

Explaining the process of assigning arguments to a char array in code

Can someone explain the code snippet below to me? Specifically, what is the significance of the line *line++ = '\0'; in the parse function? How does it differ from line[i] = '\0' and i++;? Furthermore, what does *argv++ = lin ...

Exploring GatsbyJs: Optimal Strategies for Storing Strings and Text on Static Websites

Currently in the process of building a website using Gatsby JS and Material UI. I'm wondering about the best approach for storing the site content. This website will serve as a promotional platform for a small business. Should I store the text direct ...

A guide on simulating HTTP methods in Jest when dealing with private methods

I'm grappling with how to simulate the following functionality. I need to simulate both methods: getAllBookInCategory, deleteBookInCategory The public method invokes private methods and I presume I don't need to test private methods, only callin ...

What is the proper way to implement JQuery within a constructor function contained in a JavaScript namespace?

Yesterday I ran into a problem when asking about using JQuery inside a JavaScript constructor function within a namespace. There was a bug in my code that caused me to get the answer to the wrong question. var NS=NS||{}; NS.constructor=function() { t ...

The use of JSON.parse does not support parsing URL links

As a junior developer specializing in Javascript and Google Apps Script, I decided to enhance the functionality of my Google Sheets by tracking the last modification time of URLs stored in them. Although I attempted to create a script for this task, it see ...

Change every request's URL in $http through AngularJS globally

Let's consider a basic scenario: $scope.whatDoesTheFoxSay = function(){ $http.post("/backend/ancientMystery", { ... Is there a way to alter the URL for all post requests globally? I essentially want to add a prefix to every http request. I atte ...

JavaScript: Organizing values based on their case sensitivity

Imagine a scenario where we have models ABC23x, ABC23X & abc23X all referring to the same model. These model names are retrieved from API endpoints. Now the UI has two tasks: Display only one model name (ABC23X) When calling the REST API, we need to sen ...

Validation of the top-level URL

How can I validate or filter only the top-level URL/domain using JavaScript or PHP? This filter should also accept new domain extensions, for example: Valid URL: and so on... Invalid URL: and so on... Subdomains are also not allowed! I need this val ...

Using the useState() hook with a component as an argument

I have a unique idea for my app - I want the App component's state to store another component that it will render. This way, any component should be able to update the state and trigger a re-render of the App component. function HomePage() { retur ...

I am looking to modify a particular value within an array of objects, but for some reason, the update is not being applied correctly

When attempting to copy the array, I update the selected value of a specific object based on the matching memberId. This process works well for a single member, however, issues arise when there are multiple members as the updating doesn't work correct ...

Decoding json data with targeted API keys

Looking for some assistance here. I've got a JSON data set that looks like this: [ { "positive": 2, "negative": 4 }, { "positive": 9, "negative": 18 }, { "positive": 6, "negative": 12 } ...

Tips for utilizing an npm package in conjunction with Hugo

I created a basic hugo site with the following command: hugo new site quickstart Within the layouts/_default/baseof.html file, I have included a JavaScript file named script.js. Inside script.js, the code looks like this: import $ from 'jquery' ...

angular-ui-tab-scroll: Odd spacing between blocks and tabs, each separated individually

Greetings! I would like to express my gratitude for this wonderful library! However, I am encountering an unusual issue when trying to wrap a tabset with tabs that are included separately. This can be done either by adding individual tab elements manually ...

Guide to adding a checkbox to a JavaScript list

I'm currently working on building a task list using JavaScript. The concept is to type something into the input field and then, when the user clicks the button, a checkbox with that text will be generated. However, I'm facing an issue as I am no ...

Convert Python strings into HTML JavaScript blocks using Jinja2

Having trouble passing a string to an HTML page in the "<script>" block. I am currently using Python, Flask, and Jinja2. Python code: def foo(): return myString #"[{title: 'Treino 7-Corrida',start: '2015-12-08',color: '#d ...