Mapping objects from one to another using AngularJS

I need to create a mapping of the $scope.filters object to a new variable called criteria, based on whether the original fields are null or not.

For example:

$scope.filters = {
    name: 'myName',
    lastName: null,
    age: null,
}

The desired output for criteria should only contain non-null values, like this:

var criteria = {
    name: 'myName';
}

I attempted the following logic:

var criteria = {};

angular.forEach($scope.filters, function (value, key, obj) {
        if (value != null) {
            this.push(obj)
        }
}, criteria);

However, it seems that I am missing some key aspect in my approach.

Answer №1

criteria should be treated as an object, not an array. Attempting to push it as if it were an array will not work. To properly store separate individual criteria, consider converting it into an array or using the code this[key] = value;

Answer №2

This is the recommended way to approach it:

$scope.filters = {
  name: 'myName'
  lastName: null,
  age: null,
 }

var criteria = []; //make sure to use an array instead of an object
    angular.forEach($scope.filters, function(value, key) {
      if (value != null) {
            this.push(key + ': ' + value);
        }

    }, criteria);  

expect(criteria).toEqual(['name: myName']);

I hope this clears things up for you.

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

Transform an array containing objects for convenient manipulation

I am attempting to manipulate an array using parse, push, and save data commands, but it seems like the code is not working properly. Can anyone offer assistance? I am very new to programming and just trying to improve my skills. The array should contain ...

React Js: Error encountered while parsing JSON due to an unexpected token < at the beginning

I am having issues fetching my JSON file in React JS using the fetch method. An error is popping up that says: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 I am unable to figure out what the error could be, even after va ...

Having trouble retrieving JSON data using http.get method, as the status returned is -1

I'm a beginner in AngularJS. I'm attempting to retrieve JSON data in my code using $http.get, but it's throwing an error and the status is showing as -1. What could be causing this issue? RecordApp.factory('recordaccess', [' ...

Using Node.js with Express, the Router.use() method expects a middleware function as an argument, however, it received a different type: ' +

As I delve into the world of back-end development using node and express, my current project involves creating a back-end for a simple blog with posts and user authentication. This will be utilized later in an angular 4 application. While testing the "Pos ...

What is the best way to create a regex pattern that can effectively split two consecutive mathematical operators ("/-", "*-") from a given string equation?

Struggling to convert a string equation into an array of numbers and operators, but having trouble getting it right. Here is the regex I've tried: Input: '1+2-33/45*78'.split(/([\+\-\*\/]+)/) Output: ["1", "+", "2", "- ...

Customizing WooCommerce: Renaming Dimensions Label

Within the WooCommerce products data table, there is a default attribute labeled dimensions that accepts values in the format LxBxH. I am interested in customizing this label from dimensions to packaging dimensions, both in the front-end and ideally in the ...

Can the <input type="file"> element trigger File Explorer to open automatically?

Is it possible for the input type "file" to automatically open file explorer, or is jquery/javascript required to trigger the File Explorer dialog? Any tips or tricks on how to achieve this would be greatly appreciated! Thank you in advance for your assis ...

Attempting to mark fields as required with asterisks using React Final Form in a React project

Is there a way to display an asterisk next to a label on a form using React Final Form? Here is what I have tried: <Field name="requestDescription" {...(<span style={{ color: 'red' }}>*</span&g ...

Capture various data points in an array with each click

I am currently working on a menu of buttons where users can select multiple options at the same time. My goal is to record all selected buttons in one array instead of individual arrays for each button. The end result I hope to achieve is an array like t ...

Can you explain the significance of "=>" in a context other than function invocation?

Working my way through the freeCodeCamp JavaScript course has left me quite puzzled about arrow functions. I know how to write a function using arrow notation, like this: const myFunc = () => "value"; However, in one of the later challenges, ...

The options object provided for Ignore Plugin initialization in Webpack 5.21.2 does not conform to the API schema, resulting in an error

Here is the setup of my webpack.config.js on a backend server running webpack version 5.21.1: /* eslint-disable */ const path = require('path'); const webpack = require('webpack'); module.exports = { target: 'node', modul ...

PHP redirect malfunctioning, yet still functioning?

After making some changes to the structure of my website, I seem to have broken the script somehow. When a user fills out a form correctly, they should be redirected to the appropriate page. However, the page just hangs. Strangely, the form works fine when ...

Learning how to extract data from XML and insert it into HTML using JavaScript (Novice)

--Simplified Code Update-- I'm in a bit of a tricky situation here. According to w3schools, my code should be functioning properly, but for some reason, it's just not working as expected. Here's the code for my JavaScript. XHTML <!DOCT ...

Firebase and Angular 7 encountered a CORS policy block while trying to access an image from the origin

I am attempting to convert images that are stored in Firebase storage into base64 strings in order to use them in offline mode with my Angular 7/Ionic 4 application! (I am using AngularFire2) However, I encountered an error message stating: Access to i ...

What is the best way to retrieve the results of an indexedDb request beyond the limitations of its callback function?

I am working on a form that has an input box which I want to auto-complete with values from an IndexedDb objectStore. Currently, it is functioning with two overlapping input boxes, using a simple array. However, I am looking to make it work with the values ...

Leveraging Next Js with an external REST API for streamlined authentication and authorization functionality

I am currently working on transitioning my existing application that was developed with Node.js and Express, along with a front end built using create-react-app with Redux, to Next.js. However, I have hit a roadblock as I am unsure of the correct method ...

"Contrary to the body onload event, the window.onload event does not

So, this is my first time asking a question here. Hopefully I am providing all the necessary information. My issue is with using window.onload to display a page scripted in the head of my HTML code with type="text/view". When I tried putting the code in t ...

Is it possible to retrieve several columns using the pluck method in Underscore.js following the input from the where method, similar to LINQ

var persons = [ {name : "Alice", location : "paris", amount : 5}, {name : "Bob", location : "tokyo", amount : 3}, {name : "Eve", location : "london", amount : 10} ]; var filteredResults=_.pluck(_.where(persons, {location : "paris"}), 'nam ...

What could be causing Ember/handlebars.js to prepend 'app/' to my template file names?

Whenever I try to load my Rails ember app, I encounter a frustrating issue where Ember is unable to locate the application and index templates. Ember.TEMPLATES['application] and Ember.TEMPLATES['index'] Oddly enough, when I check Ember.TEM ...

The function you are trying to access does not exist in this.props

Trying to pass this.state.user to props using the isAuthed function is resulting in an error: this.props.isAuthed is not a function . The main objective is to send this.state.user as props to App.js in order to show or hide the Sign out button based on ...