Generate an array of image categories from an array of image objects

I have an array of Objects that looks like this:

$scope.images = [
      {key: 'shop1/images/a1.jpg'},
      {key: 'shop2/images/a2.jpg'},
      {key: 'shop1/images/a3.jpg'},
      {key: 'shop3/images/a4.jpg'}    
    ]

My goal is to transform the above JSON into the following array of objects:

[
      { 'key':'shop1', 'images':['shop1/images/a1.jpg', 'shop1/images/a3.jpg'] }
      { 'key':'shop2', 'images':['shop2/images/a2.jpg'] }
      { 'key':'shop3', 'images':['shop3/images/a4.jpg'] }
 ]

Check out the fiddle here: http://jsfiddle.net/ojehojf8/

Answer №1

Do we really need to use an array?

Why not just utilize an object as explained in this tutorial on creating hash or dictionary objects in JavaScript

You can achieve the desired result with code similar to the following:

angular.forEach($scope.images, function(obj){
    $scope.imgsObj = {};
    var res = obj.key.split("/");
    if($scope.imgsObj[res[0]]){
      $scope.imgsObj[res[0]].push(obj);
    }else{
      $scope.imgsObj[res[0]] = [obj];
    }
}

Answer №2

Angular is not required for this particular task:

var images = [
      {key: 'shop1/images/a1.jpg'},
      {key: 'shop2/images/a2.jpg'},
      {key: 'shop1/images/a3.jpg'},
      {key: 'shop3/images/a4.jpg'},
      {key: 'shop1/images/a5.jpg'},
      {key: 'shop2/images/a6.jpg'},
      {key: 'shop1/images/a7.jpg'},
      {key: 'shop1/images/a8.jpg'},
      {key: 'shop3/images/a9.jpg'},
      {key: 'shop2/images/a10.jpg'}      
]

// Start by organizing the data based on keys
var result = {};
for (let i = 0; i < images.length; i++) {
  let key = images[i].key.split('/')[0];
  if (!result[key]) {result[key] = [];}
  result[key].push(images[i].key);
}

// Convert the organized data into the desired format
var arr = [];
for (let i in result) {
  if (!result.hasOwnProperty(i)) continue;
  arr.push({key: i, images: result[i]});
}

console.log(arr)

As a bonus, here's a one-liner version of the same functionality:

var images = [
      {key: 'shop1/images/a1.jpg'},
      {key: 'shop2/images/a2.jpg'},
      {key: 'shop1/images/a3.jpg'},
      {key: 'shop3/images/a4.jpg'},
      {key: 'shop1/images/a5.jpg'},
      {key: 'shop2/images/a6.jpg'},
      {key: 'shop1/images/a7.jpg'},
      {key: 'shop1/images/a8.jpg'},
      {key: 'shop3/images/a9.jpg'},
      {key: 'shop2/images/a10.jpg'}      
]



var result = images.map(img => img.key.split('/')[0]).filter((v, i, a) => a.indexOf(v) === i).map(k => {return {key: k, images: images.filter(img => img.key.split('/')[0] === k).map(img => img.key)}});
console.log(result)

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

Tips on implementing live updates in Firebase without the need for reloading the page

After a user changes their profile picture, the update does not appear until they refresh the page. Here is the code snippet causing this issue: const handleProfile = async (e: any) => { const file = e.target.files[0] const storageRef = firebase ...

Transitioning in Vue.js can be triggered by changing a value up or down

My current transition block component is set up like this: <div v-if="!surveyResultIsReady" class="vh-md-40 position-relative" > <transition name="custom-classes-transition" enter-active-class="animated slideInRight" ...

Passing a class as a parameter in Typescript functions

When working with Angular 2 testing utilities, I usually follow this process: fixture = TestBed.createComponent(EditableValueComponent); The EditableValueComponent is just a standard component class that I use. I am curious about the inner workings: st ...

Tips for showcasing model data dynamically on a webpage using HTML

My model is constantly updating within a function, and I need a way to dynamically display this updated data without the need to refresh the page. How can I achieve this? models.py class MyLongProcess(models.Model): active_uuid = models.UUIDField(&apo ...

Conceal an element from view upon clicking on it

Task at Hand : Implement a smooth element hiding effect upon clicking, similar to the behavior on this website , where the letter A fades away smoothly when clicked. Is it possible to achieve this effect using only HTML, CSS, and JavaScript? var t ...

What is the top choice for creating a shallow copy of an array

While delving into the vue source code today, I stumbled upon a method of writing that left me puzzled. view source const deduped = [...new Set(pendingPostFlushCbs)] My initial thought is that it is a shallow copy of the array. But why is there a need t ...

Looking to extract data from a Json object and add it into a table

<!DOCTYPE html> <html> <head> <script type="text/javascript"> function displayJsonData() { var jsonData = { "cars": [ '{"model":"Sentra", "doors":4, "features":["hi"," ...

"Searching for the index of a clicked element? Here's how to do

I am trying to determine the index of a clicked anchor element in my navigation using jQuery. However, when I use the following code snippet, I always get zero in the console: $('.navigation ul li a').click(function(e) { e.preventDefault(); ...

Utilizing Conditional Statements in the @artsy/fresnel Framework

I recently started working on a responsive React application using the @artsy/fresnel npm package. Below is a snippet of the code I have implemented: <Media greaterThanOrEqual='computer'> <div style={{ padding: '20px 50px' ...

Organizing identical array elements in PHP participants into groups

I created a function to detect word sequences: function checkSequence($arrScheme = [], $arrInput = []) { $sequenceNeeded = array_values(array_intersect($arrScheme, $arrInput)); if(!empty($arrInput) && ($sequenceNeeded == $arrIn ...

When a user clicks the button for the second time in React, the UI remains static and does not re-render

I recently started working with React and decided to build an app using the Open Weather Map API. The idea is that when a user enters a location and clicks the Find button, a JSON file is retrieved and displayed on the UI. However, I encountered an issue ...

The image tag fails to appear on the browser when the client attempts to access it

Greetings, I am new to web development. I am attempting to create a simple static website that only displays an image in the header tag of an HTML file. The server seems to be working correctly in sending responses to the client, but the problem lies in t ...

Docusaurus font loading specifically optimized for body text, excluding headings

I've added the following CSS code to my Docusaurus custom stylesheet: @import url("https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500;1,600;1,700&display=swap"); :root { --ifm-color- ...

Error encountered when executing MySQL query using Node.js

I am trying to use Node JS and MySQL to check if a user already exists in the database. I have included the code snippet below: var username = "RandomUsername"; var email = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5b093 ...

An absence of data causes the function to malfunction

One of the components in my application is responsible for rendering select elements on the screen, allowing users to dynamically order data. The initial state is as follows: state = { sortBy: [ { author: 'asc' } ] }; In this s ...

"Make sure to tick the checkbox if it's not already selected,

Could use some assistance with traversing and logic in this scenario. Here is the logic breakdown: If any checkbox in column3 is checked, then check the first column checkbox. If none in column 3 are selected, uncheck checkbox in column1. If column1 ...

Clickable link in popup window using fancybox

When I try to use fancybox to open an iframe and scroll to an anchor tag, it works perfectly in IE but not consistently in other browsers. It stops at a different place than the anchor. I suspect the issue may be related to JavaScript based on information ...

The PUT method in the Node Express app is only functioning six times

I have set up my database with Mongodb to handle variable updates. Additionally, I am utilizing node.js along with an express server. Take a look at the code snippet below: router.route("/update/").put( async (req, res) =>{ const count_up ...

Ways to provide information to an rxjs observer

It appears that most people find observers to be a piece of cake, but I personally struggle with them. I am trying to set up an observable that can receive a number input after it has been created, triggered by pressing a button. However, all the examples ...

Store and Persist Data for a Model in MongoDB

Currently working through the MongoDB and Mongoose section on FreeCodeCamp. The challenge involves creating a document instance using the Person constructor previously built. The object passed to the constructor should have fields for name, age, and favor ...