Generating a JSON object through the comparison of two other JSON objects

I need to create a new JSON object called selectedProductAttributes, which is generated by comparing the contents of a second JSON object (selectedProductAttributesNames) with a third object (allProductAttributes). Let me provide some examples to make this clearer.

The first example, called allProductAttributes, is a JSON object containing various attributes for form fields:

$scope.allProductAttributes = [
        {
            name: 'postcode',
            title: 'Postcode',
            required: true,
            type: 'text',
            max: '10',
            placeholder: 'Enter a postcode'
        },
        {
            name: 'Term',
            title: 'Contract term',
            required: true,
            type: 'number',
        },
        {
            name: 'bandwidth',
            title: 'bandwidth',
            type: 'select',
            options: [
                {id: 10, name: '10 mb/s'},
                {id: 100, name: '100 mb/s'},
                {id: 1000, name: '1000 mb/s'},
                {id: 10000, name: '10000 mb/s'}
            ]
        },
        {
            name: 'service',
            title: 'Service',
            required: true,
        }

]

The next JSON object, selectedProductAttributesNames, contains a list of the form fields that the user wants to select from allProductAttributes:

$scope.selectedProductAttributesNames = [
"postcode",
"service"
]

So when the user selects 'postcode' and 'service' in selectedProductAttributesNames, a new JSON object should be created with the corresponding form field attributes from allProductAttributes:

$scope.selectedProductAttributes = [
    {
            name: 'postcode',
            title: 'Postcode',
            required: true,
            type: 'text',
            max: '10',
            placeholder: 'Enter a postcode'
        },
    {
            name: 'service',
            title: 'Service',
            required: true,
        }
]

If this explanation is unclear, please let me know. Can anyone suggest how I can achieve this? Thank you!

Answer №1

Instead of starting from scratch, you could utilize underscore to achieve the following:

$scope.selectedProductAttributes = _.compact($scope.allProductAttributes.map(function (item) {
    return _.contains($scope.selectedProductAttributesNames, item.name) ?
            item : false}))

If you're not concerned about supporting outdated browsers like IE 6, 7, or 8, and prefer not to rely on external libraries, you can opt for this alternative approach:

$scope.selectedProductAttributes = $scope.allProductAttributes.filter(function (item) {
    var validated = false, i, length = $scope.selectedProductAttributesNames.length;
    for (i = 0 ; i < length; i++) {
        if (item.name == $scope.selectedProductAttributesNames[i])
            validated = true;
    }
    return validated
})

Answer №2

If you possess the capability to adjust the attribute source object slightly in accordance with the following style, employing dictionary-style access to your objects and a loop will provide you with the desired outcome.

$scope.chosenProductAttributes = {
   'zipcode' : {
      'name': 'zipcode',
      /// additional details go here
   },
   /// other attributes listed here
};

for (var i = 0, length= $scope.chosenProductAttributes.length; i < length; i++) {
  $scope.chosenProductAttributes[x[i]] =    
     $scope.chosenProductAttributeNames[x[i]];
}

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

Which one to use: Response JSON object or JSON.stringify()?

If I have JSON content that I want to return, what is the best way to do it? let data = { x: 'apple', y: 'banana' }; Is it better to: A) Return the object as is when sending the response with res.send(data)? B) Convert the objec ...

Eliminate the JSON object within jqGrid's posted data

The web page I'm working on features Filters with two buttons that load data for jqGrid when clicked. Clicking 'Filter' generates a postData json object and sends it to the server, which is working perfectly. However, I'm facing an is ...

Can you explain the distinction between bodyparser.urlencoded and bodyparser.json?

I'm a bit confused about the use of bodyparser. Why is it necessary when we can simply use json.stringify (to convert an object to a string) and json.parse (to convert JSON to an object)? Is it because by using app.use() with bodyparser, the middlewa ...

How to use a string condition to filter a list of objects in Javascript?

Below is the structure of the object: var objList = [ { "age": 19, "valueField": 34, "booleanField": false }, { "age": 15, "valueField": 5, "booleanField": false }, { "age": 22, "valueField": 17, "booleanField": true } ]; Given the condition ...

Leveraging data schemas to manage the feedback from APIs

I am curious about the benefits of modeling the API response on the client side. Specifically: First scenario: const [formData, setFormData] = useState(null); ... useEffect(() => { const callback = async () => { try { const fetchDa ...

Struggling to store information in a MongoDB database within my MEAN Stack project

After successfully creating a collection for user LOGIN/LOGOUT and managing to store and retrieve data using Express app and mongoose, I encountered an issue when trying to create another collection. Despite successfully creating the collection, the data w ...

Click on the window.location.href to redirect with multiple input values

I am facing a challenge with my checkboxes (from the blog label) and the code I have been using to load selected labels. However, this code seems to only work for one label. Despite multiple attempts, I have found that it only functions properly with one ...

Utilize Android to Extract Data from JSON

I am attempting to retrieve and parse the list of 4chan boards using their json api. The JSON data I am trying to parse can be found here: . Upon verification, the json appears to be valid. However, I am encountering the following error message: 11-21 17 ...

Gather all dropdown items using WebdriverIO and store them in an array

Within my application, there is a dropdown that resembles the following - <select> <option value="1">Volvo</option> <option value="2">Saab</option> <option value="3">Mercedes</option> <option value="4"& ...

Ways to conceal the form utilizing ng-click?

I have created a search form that displays product details when the ng-click button is clicked. After receiving the product details, I wish to hide the form. product.html <form name="search_form"> <div class="search" flex layout="row" layout-a ...

Guide to Subscribing to a nested observable with mergeMap within a button's click event

The issue arises in the "addToWishlist" function as I attempt to concatenate the result of the outer observable with the inner observable array and then call the next method on the inner observable. The "addToWishlist" method is triggered by the click ha ...

Personalized Angular dropdown menu

Recently, I've started delving into angularJS and I'm eager to create dropdowns and tabs using both bootstrap and angular. Although there is a comprehensive angular bootstrap library available, I prefer not to use it in order to gain a deeper und ...

Is Json Patch in contradiction with the principles of REST?

Is it against REST principles to use Json Patch? Will my API still be considered RESTful if I implement it? { "op": "replace", "path": "/biscuits/0/name", "value": "Chocolate Digestive" } ...

What is the best way to create a dynamic icon using React and TypeScript?

Excuse me, I am new to using React and TypeScript. I'm having trouble getting the icon to change based on the status in AppointmentType. The body color is working fine, but the icons are not changing. Can someone please help me solve this issue? const ...

Open a new lead form in Crm 2013 by clicking a button and automatically passing the details of the

I have integrated an Add New Lead button into the main form on the Homepage for contacts. Clicking this button triggers a script that opens a new form and passes "Crm Parameter FirstSelectedItemId" as a parameter. By selecting a contact and clicking crea ...

Discovering ways to optimize argument type declarations in TypeScript

If we consider having code structured like this: function updateById( collection: Record<string, any>[], id: number, patch: Record<string, any> ): any[] { return collection.map(item => { if (item.id === id) { return { ...

Is it possible to encounter a MongoDB error for the $or operator in a correctly formatted query?

Here is the problem I am facing: const users = this.mongo.db.collection('Users') let query = { '$or': [ { "email": {'$eq': req.body.email }}, {"username": {'$eq': req.body.username }} ] } users.fi ...

Upon reloading, the dynamically generated table does not appear accurately

When a table is dynamically created using JavaScript/jQuery/html from an Ajax call, it initially displays correctly formatted. However, upon refresh/reload, the formatting of the table becomes incorrect. To address this issue, I have implemented a Promise ...

Using AXIOS and VueJs to visually represent data with a two-dimensional array

I'm new to vuejs and I want to display my data response in a two-dimensional table. This is the data I have: [{ "origine": "", "nb": 15 }, { "origine": "?", "nb": 18 }, { "origine": "?L", "nb": 1 }, { "origine": "G", "nb": 298 }, { ...

I can't figure out why the data in this JSON string keeps altering within my ajax function

I am encountering an issue with passing an array of JSON objects to my controller. Despite appearing well-formed and correctly populated when I insert an alert before the ajax call, some variables are showing null values when inspecting the payload of the ...