Tips for utilizing the 'map' function with nested arrays within an array (JSON)

Below is the JSON data provided:

users = [{
  "name": "alex", 
   "id":123, 
   "surname":"xx", 
    tarriff: {
      "id":1,
      "name":"free"
    }
},
 {
  "name": "tom", 
   "id":124, 
   "surname":"henry", 
    tarriff: {
      "id":1,
      "name":"free"
    }
}

]

I am seeking assistance in filtering this data (specifically removing "surname":"xx", "surname":"henry" and others).

When attempting to use tarriff.name, it results in a syntax error.

$scope.userfilter = users.map(({name,id, tarriff.name}) => ({name, id, tariff_name}));

Please help me in finding the correct solution for this problem.

Answer №1

To create a new object with shorthand properties, you can utilize a destructuring assignment.

var users = [{ name: "alex", id: 123, surname: "xx", tarriff: { id: 1, name: "free" } }, { name: "tom", id: 124, surname: "henry", tarriff: { id: 1, name: "free" } }],
    result = users.map(({ name, id, tarriff }) => ({ name, id, tarriff_name: tarriff.name }));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

The variable users you have defined is of type object, not an array. It appears to be a common mistake and what you are actually trying to achieve is filtering an array. To filter an array, you should utilize the filter method as demonstrated below:

const users = [
  {"name": "alex", "id":123, "surname":"xx", tarriff:{"id":1,"name":"free"}},
  {"name": "emma", "id":123, "surname":"yy", tarriff:{"id":2,"name":"anna"}}
];

const criterion = "free";
const filteredUsers = users.filter(user => user.tarriff.name == criterion);

console.log(filteredUsers)

Answer №3

It can be quite challenging to comprehend your exact needs. My assumption is that you are interested in deep mapping rather than Array.filter.

The error in syntax arises from incorrect de-structuring. Here is a more proper approach:

$scope.userfilter = users.map( ({name, id, tarriff: { name: tarriff_name }}) => {
    return {name, id, tariff_name};
});

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

Inquire data using a SQL-style query in JSON format with

I have a collection of JSON data that I need to store in Redis. { "foo": "37", "bar": "Alex", "baz": "Tom", "type": "test", "date": "12/12/2012 12:12:12 } Since my background is in SQL, I'm not entirely sure about the best approa ...

Tips for utilizing SlowCheetah to modify array elements within a Json configuration file

Today is my first time working with SlowCheetah to transform a JSON configuration file. I am facing an issue where I cannot figure out how to transform an array of settings. For instance, if my original config file contains the following setting: { "Set ...

Previous Button on jQuery/Javascript Slider Not Functioning

Having a small issue with my previous button, #prev, as it is not scrolling back to the previous image but instead to the next image. This is the script I am using: http://jquery.malsup.com/cycle/int2.html Additionally, when I try to set the width of the ...

Transitioning the existing application from iOS Cordova's UIWebView to WKWebView requires disabling asynchronous JavaScript execution in order to maintain functionality

Previously, in one of our older examples for saving data, we had successfully used the following code in cordova UIWebview without any issues: var filenameID; function getFilenameID() { $.ajax('/jquery/getdata', // request url { success ...

Jackson Password Serialization for Enhanced Security

Currently, I am utilizing Jackson to serialize objects for storage in MongoDB using Jongo. Within these objects is a password hash that needs to be stored in the database. Furthermore, there is a REST API set up to retrieve these objects. However, upon se ...

Tips for saving a JavaScript object into a JSON file

Let's discuss how to save the following data: myJSONtable into a JSON file using the following method: fs.writeFile('./users.json', JSON.stringify(myJSONtable, null, 4), 'utf-8', function (err) { if (err) throw err ...

SVG to PDF conversion is successful with Plotly.js, however, C3.js is currently experiencing issues with this

After an onclick event, I am using css2pdf to save my svg chart to pdf. It functions perfectly with plotly.js, but unfortunately not with c3.js - you can check out my fiddle here: http://jsfiddle.net/3hs7cs4f/ I suspect the issue lies within the c3.js svg ...

Exploring the Express problem with AWS SNS web service subscriptions using a Sinatra case study

I'm currently working on developing an auto-subscription API that sends back a token via POST. While I have successfully implemented this in Sinatra (rendering the POSTed JSON from AWS), I'm facing challenges with Express. I believe it's jus ...

Modifying the color of a specific node in jstree

I am attempting to modify the background color of the node I have selected in jstree. $('#syncrep').jstree({ 'core' : { 'data' : repository ...

Issue with Custom Tooltip in Mootools 1.2 - Images displaying prematurely before hover action

Encountering an issue with Mootools 1.2 Tips (custom tooltips) We are currently utilizing Joomla with the latest update that includes Mootools 1.2, and I am working with the following JS code: $$('.tipz').each(function(element,index) { ...

Obtaining a JSON reply using Ember

Exploring new possibilities with Ember js, I am eager to switch from fixtures to using an API. Below is the code I have implemented to fetch the data: App.ItemsRoute = Ember.Route.extend({ model: function() { return $.getJSON('http://som ...

Iterate over the key-value pairs in a loop

How can I iterate through a key-value pair array? This is how I declare mine: products!: {[key: string] : ProductDTO}[]; Here's my loop: for (let product of this.products) { category.products.push((product as ProductDTO).serialize()); } However, ...

Avoiding duplication of user input within a 2D matrix in Java

Is there a way to prevent the user from entering two values for the same spot in a 2D array? Consider this scenario: in a game of battleship, players input coordinates for ship placement on a 2D array playing board. Ships cannot overlap, so how can you ge ...

Deactivate a Specific Popup for a Specific Page

In my project, I have a file called modal.php that contains two modal windows: Login Modal Feedback Modal The Login Modal automatically pops up every 5 seconds for users who are not logged in. The Feedback Modal opens when clicked. On my website, I hav ...

Struggling to achieve desired output from function in NextJS

I'm a bit confused by the code below. The itmLoop function seems to work fine when placed directly in the return section, but nothing is output when it's called as shown below? I'll eventually need to make it recursive, so I have to keep i ...

Unable to retrieve all AJAX responses during page loading in Puppeteer

When loading the URL here, I notice around four AJAX calls in the network tab. However, when using Puppeteer to scrape the data, only one response URL from an AJAX call is being logged: I have attempted the following code: async function main() { try { ...

Parsing Multidimensional JSON Arrays Using ASP.NET Core

I've been troubleshooting this issue for a few days now, but it seems I might be overlooking something. Following Microsoft's recommendations, I constructed my sample application using GitHub as a reference: https://learn.microsoft.com/en-us/asp ...

Sequelize transforms any given date object into a local date representation

When running a query with a data replacement, the date is not set as UTC in the query. Here's the code snippet: let startInterval = moment('2020-12-09').toDate(); db.query(` SELECT kv.kpiId FROM kpiValues kv WHERE kv.insertDate ...

Rendering items in a list with React does not just display the last item on the list

I encountered an issue where, when I retrieve data from an API and add it to the state's array, I only see the last list item even though the mapping process is supposed to include more than 1 item. const [items, setItems] = useState([]); con ...

Discovering ways to monitor Service Providers

What Currently in my AngularJS project, I am attempting to monitor certain internal functions such as angular.module and serviceProvider. How Fortunately, I have managed to keep track of calls to angular.module successfully. var moduleCalls = spyOn(an ...