What is the process of transforming an array into a string URL with AngularJS?

As a novice in AngularJS, I am currently working on a simple application.

This is the HTML code snippet that I am dealing with:

<table class="table" ng-repeat="(attr, assets) in customize.product.attributes">
    <tr>
        <th colspan="2">{{attr}}</th>
    </tr>
    <tr ng-repeat="asset in assets">
        <td>
            {{asset}}
        </td>
        <td>
                <file-uploader class="form-control"
                    image-width="{{galleryConfigs.width}}"
                    image-height="{{galleryConfigs.height}}"
                    image-crop-width="{{galleryConfigs.width}}"
                    image-crop-height="{{galleryConfigs.height}}"
                    max-size="5000"
                    allowed-extensions="png,jpeg,jpg"
                    result-model="customize.assets[attr][asset]">
                </file-uploader>
        </td>
    </tr>
</table>

And this is my JavaScript code:

$scope.create = function(published){
        var published = published || false,
            customize = angular.copy($scope.customize);

        if(published)
            customize.published = true;

        dataProvider.Customize.save(customize).$promise
        .then(function(_customize){
            if(!_customize) throw 'Error System';

            toast.create({content:'Succes', className:'success'});
            $state.go('pos.product.customize.show',{customizeId:_customize.id});
        }).catch(function (error){
            $log.error(error);
        });
    };

When I save the data, it ends up being stored like this:

"assets" : {
    "part 1" : {
        "black" : [ 
            "/file/c36a3297-11bb-4028-8cb7-d750b98436ec.png", 
            ...
        ],
        "red" : [ 
            "/file/c36a3297-11bb-4028-8cb7-d750b98145ec.png", 
            ...
        ]
    }
}

However, I wish to save the data in the following structure:

"assets" : {
    "part 1" : {
        "black" :"/file/a11c553f-de74-48e2-93a0-6fc72a54fa9b.png",
        "red"   :"/file/a11c553f-de74-48e2-93a0-6fc72a54ga8c.png" 
    }
}

Is there any way to achieve this?

Answer №1

When considering that assets may consist of multiple components, here is a solution that retrieves the first item in each color array:

var selection = _.mapObject(assets, function(asset){
    return _.mapObject(asset, _.first);
});

This approach is akin to the response provided yesterday for the inquiry How to convert data array into an object using JavaScript?

var assets = {
    "part 1" : {
        "black" : [ 
            "/file/c36a3297-11bb-4028-8cb7-d750b98436ec.png", 
            "/file/4a6ec1ed-c3b1-48f9-84c0-61dd0f6da08a.png", 
            "/file/c66ac97a-18be-4e79-9ec1-ca67ab37d3f3.png"
        ],
        "red" : [ 
            "/file/c36a3297-11bb-4028-8cb7-d750b98145ec.png", 
            "/file/4a6ec1ed-c3b1-48f9-8cb7-61dd0f6da07a.png", 
            "/file/c66ac97a-18be-4e79-8cb7-ca67ab37d3c3.png"
        ]
    }
}

var selection = _.mapObject(assets, function(asset){
return _.mapObject(asset, _.first);
});

document.getElementById('results').textContent = JSON.stringify(selection);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore.js"></script>

<pre id="results"></pre>

Answer №2

Check out this handy function for converting an array into an object:

function transformArrayToObject(arr) {

   //Initialize an empty object
   var obj = {};

   //Iterate through the array and assign elements as properties to the object
   arr.forEach(function(element, index){
      obj[String(index)] = element;       
   }) 

   return obj;

}

With this function, ['apple', 'orange', 'grapes'] turns into

{1: 'apple', 2: 'orange', 3: 'grapes'}

If you're looking to create an object with a single property that combines all array elements into a string, here's how it can be done:

function transformArrayToObjWithOneProperty(arr) {

       //Create an empty object
       var obj = {value: ''};

       //Concatenate array elements as a string within the object
       arr.forEach(function(element){
          obj.value = obj.value + element + ',';       
       }) 

       return obj;

}

This function will change ['apple', 'orange', 'grapes'] to {value: 'apple,orange,grapes'}

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

Borderless thumbnails in the stunning blueimp Gallery

My website is utilizing blueimp Gallery, however, the thumbnails are displaying with a white border. The live demo does not have this border. I have attempted to adjust the thumbnail size to match the demo (86x86px), but that did not fix my issue. After re ...

The error message "Seed is not defined" is raised when the program attempts to

I'm currently diving into fullstack vue and I'm perplexed by the error occurring in this particular scenario. window.Seed = (function () { const submissions = [ { id: 1, title: 'Yellow Pail', ...

Obtain the HTML link embedded within the DOM header element resource, without relying on any identifiers such as ID

My website has the following code structure: <link rel="amphtml" href="http://example.com/?amp"></head> I want to extract the html link only on pages where the "amphtml" rel value is present. I attempted this code, but it causes issues on URL ...

I am on the lookout for an Angular 2 application that utilizes Gulp to generate a distribution folder with the newest @angular frameworks

I'm on the lookout for an Angular2 application that incorporates Gulp to generate a 'dist' folder using the most recent @angular libraries. Although I've come across some online examples, they do not utilize the latest @angular librari ...

Having two components, JQuery's .attr handles attributes efficiently

I'm currently working on a JQuery script that aims to modify the attributes of another script, but I've encountered an unexpected token error. The problem seems to be caused by the presence of a "-" in between the two attributes I'm trying t ...

Subcomponent in React is not rendering as expected

I have a primary React component with a subcomponent named AttributeInput. To prevent redundancy in my code, I moved some of the logic from the main component to a method within AttributeInput. My attempt at referencing this code looks like this: {this.s ...

How can we determine the total number of mandatory fields in an AngularJS form?

Can you explain how to calculate the number of required fields in a form using AngularJS? In my form, there are two required fields (email and select view). I want to display the count on my page - showing 2 if email is filled, 1 if only email is filled, a ...

Combining Multiple Results into One Unique Output using a Lodash Function

<span v-for="r in results" >{{ r.owner.first_name }} {{ r.owner.last_name}} </span> I want to ensure that only one occurrence is displayed for the result. So, with the provided code snippet, I am currently seeing: John Doe John Doe John ...

GPU-JS is encountering an issue: the kernel is being provided with an excessive number of

While attempting to create a basic script that utilizes the GPU for array multiplication, I encountered an error with the title message. I am unsure if the issue lies in my own oversight of not installing all necessary libraries or if it is a bug within th ...

a:hover CSS style altering the behavior of buttons with images in a web browser

Earlier I attempted to ask this question from my phone, but it ended up being overly convoluted and confusing. Therefore, I have decided to start fresh after locating a working PC. Unfortunately, due to the sensitive nature of the project, I am unable to p ...

Storing information in a parse table using NodeJs

I am trying to add data to a Parse table. At the top of my code, I have the line import Parse from 'parse/node';. Here is how I am inserting the data: const game = Parse.Object.extend('Game'); const query = new Parse.Query(game); que ...

Retrieving data from a child node using Jsonpath

Displayed below is a sample of JSON input data: { "India":{ "Attributes":{"Time":"2006-05-04T03:22:11.499Z"}, "ActiveCity":{ "profile":"Mumbai" }, "CurrentCities":{ "Mumbai":{"population":"121212121","Are ...

When you reach the halfway point of the page, the infinite scroll feature will be activated

I have a situation where I need to load more products from an API when the user scrolls to the middle of the page. I have successfully implemented the code for this feature, but I am facing two issues. Firstly, the function gets called multiple times when ...

How can I customize an SVG using CSS when it's being accessed from another directory on my computer?

I find myself in a bit of a bind at the moment. Within my code lies an SVG depicting a map of the United States. Upon clicking on a specific state, the entire country fades away, revealing a separate SVG displaying only that state. Each of the 50 states is ...

Unable to manage the rotation in Three.js GLTFLoader

Issue Why am I unable to rotate the angle of an object? (scene.rotation.x += 0.03;) The camera can, but the scene object cannot. I've searched for a solution for a long time without success. Here is my code: import * as THREE from 'https://un ...

Manipulating latitude and longitude variables from Javascript Geolocation in an ASP.NET environment

Attempting to retrieve user location using geolocation in JavaScript, I am able to see the current location. However, when trying to assign the coordinates variable to a C# object label, it does not return anything. Below is my JavaScript code snippet: ...

Navigating JSON data to retrieve a specific property in AngularJS using a select form

Struggling with AngularJS and JSON. I have a form.html view where users can select their province. I have a Province JSON file for the select tag, but when storing in MySQL, I need the province Id. I tried using ng-value="province.id" in the option tag but ...

Pass a JavaScript variable to a PHP script using AJAX when a button is clicked, with a dynamically set href attribute

This is the current situation: There is a checkbox on each row of a table that represents some information An initially disabled button becomes enabled when any checkbox is checked The button is enclosed by an <a></a> tag as shown: <a>&l ...

Encountering a Sails.js malfunction while attempting to modify and save a function

Encountering an issue while attempting to set up edit and update functions using Sails.js. The error occurs upon clicking the edit button. <html> <body> <table> <thead> & ...

What is the best way to pass $scope variables to a controller?

I'm currently in the process of developing a system that involves listing items with specific attributes. Title Skills Budget Date Posted Additionally, I have implemented a modal that opens up when an item is clicked in the list. My goal is to retr ...