javascript assign array to object key

Looking at this basic array:

const arr = [
  {
    "id": 2,
    "color": "red"
  },
  {
    "id": 1,
    "color": "blue"
  },
  {
    "id": 2,
    "color": "yellow"
  },
];

I am interested in constructing a hash map to update existing colors for each key.

For example, I want to add color: green to id: 3

Currently, there is no id: 3 present in the array

The expected outcome is as follows:

{
    2: [{color: "red"}]
    1: [{color: "blue"}, {color: "yellow"}],
    3: [{color: "green"}]
}

If I decide to include color: brown to id: 2

In such a scenario, I anticipate the following result:

{
    2: [{color: "red"}, {color: "brown"}]
    1: [{color: "blue"}, {color: "yellow"}],
    3: [{color: "green"}]
}

A Playground demonstration has been set up:

const arr = [
  {
    "id": 2,
    "color": "red"
  },
  {
    "id": 1,
    "color": "blue"
  },
  {
    "id": 2,
    "color": "yellow"
  },
];

function addItem(id: number, colors: any) {
    let newArr = {[id]: colors};
  arr.forEach(function (obj) {

    newArr[obj.id].push({id: obj.color});
  });
  return newArr;
}

console.log(addItem(3, [{color: "green"}]))
console.log(addItem(1, [{color: "brown"}]))

Additionally, duplicate entries should be avoided

Answer №1

const arr = [{
    "id": 2,
    "color": "red"
  },
  {
    "id": 1,
    "color": "blue"
  },
  {
    "id": 2,
    "color": "yellow"
  },
];

const groupedColors = arr.reduce((groups, current) => {
  if (!(current.id in groups)) {
    groups[current.id] = []
  }
  groups[current.id].push({
    color: current.color
  })
  return groups
}, {})

addNewItem(3, {
  color: "green"
})

addNewItem(1, {
  color: "brown"
})

console.log(groupedColors)

function addNewItem(id, item) {
  if (!(id in groupedColors)) {
    groupedColors[id] = []
  }
  groupedColors[id].push(item)
}

Answer №2

function addColorToId(id, color) {
                for (var i = 0; i < array.length; i++) {
                  if (array[i].id == id) {
                    array[i].color.push(color)
                  }
                }
              }

This function loops through the provided array and adds a specific color to the element with matching id.

Answer №3

Below is a code snippet that offers a solution to the given problem

const hashMap = new Map([
  [1, [{ color: "red" }]],
  [2, [{ color: "blue" }]],
  [3, [{ color: "yellow" }]],
]);

function addItem(id, colors) {
  hashMap.set(
    id,
    hashMap.has(id) ? [...hashMap.get(id).concat(colors)] : colors
  );

  return hashMap;
}
console.log(hashMap);
console.log(addItem(3, [{ color: "green" }]));
console.log(addItem(4, [{ color: "pink" }]));

Answer №4

let itemsArray = [{
          "id": 2,
          "color": "red"
        },
        {
          "id": 1,
          "color": "blue"
        },
        {
          "id": 2,
          "color": "yellow"
        },
      ];
      
      const groupItemsByColor = (items, key) => {
        return items.reduce(function(result, item) {
          const temp = {...item};
          delete temp[key];
          (result[item[key]] = result[item[key]] || []).push(temp);
          return result
        }, {})
      }
      
      const addNewItem = (id, colors) => {
        // const newItemsArray = itemsArray... etc if you do not want to alter the original array
        itemsArray = itemsArray.concat(colors.map(c => {
          c.id = id;
          return c
        }))
      
        const groupedItems = groupItemsByColor(itemsArray, 'id')
        return groupedItems
      }
      
      console.log(addNewItem(3, [{
        color: "green"
      }]))
      console.log(addNewItem(1, [{
        color: "brown"
      }]))

Answer №5

Utilizing a class to encapsulate your data can be advantageous in this scenario.

  1. Upon initialization, convert your array of objects into a Map with array values (an object can also be used as an alternative).

  2. Develop a method that adds new colors to the appropriate map array only if they are not duplicates.

const arr=[{id:2,color:"red"},{id:1,color:"blue"},{id:2,color:"yellow"}];

class ColorMap {
        
  // `reduce` over the array to create a `colors` Map.
  // If the id doesn't exist on the map as a key,
  // create it, and assign an empty array to it.
  // Then push in the color to the array if
  // it doesn't already exist
  constructor(arr) {
    this.colors = arr.reduce((acc, obj) => {
      const { id, color } = obj;
      if (!acc.has(id)) acc.set(id, []);
      if (!this.colorExists(id, color)) {
        acc.get(id).push({ color });
      }
      return acc;
    }, new Map());
  }
  
  // Simple check to see if the color already
  // exists in the target array
  colorExists(id, color) {
    return this.colors?.get(id)?.find(obj => {
      return obj.color === color;
    });
  }

  // Similar to the `reduce` function, if the id doesn't have
  // a key on the map create one, and initialise an empty array,
  // and if the color doesn't already exist add it
  addColor(id, color) {
    if (!this.colors.has(id)) this.colors.set(id, []);
    if (!this.colorExists(id, color)) {
      this.colors.get(id).push({ color });
    }
  }

  // Return the colors map as a readable object
  showColors() {
    return Object.fromEntries(this.colors);
  }

}

const colorMap = new ColorMap(arr);

colorMap.addColor(3, 'green');
colorMap.addColor(1, 'brown');
colorMap.addColor(1, 'brown');

console.log(colorMap.showColors());

For more information, refer to the following documentation:

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

Switch the image source when hovering over a text menu

Currently, I have been using the following code to switch between images. However, what I actually want to do is change the image when hovering over the title link of the image. onmouseover="this.src='Images/img.png'" onmouseout="this.src=' ...

Steps to launching a URL in a new window on Internet Explorer

I want it so that when button1 is clicked, the URL opens in a new window using Internet Explorer. ...

What is the best way to specify a function parameter as the `QUnit` type using TypeScript in conjunction with QUnit?

In my project, which is partially written in TypeScript and licensed under MIT, I am utilizing QUnit. I have some TypeScript functions that require QUnit as a parameter, and I would like to define their types based on its interface from the typings. For e ...

Manipulating arrays of objects with handlebars.js

I need help with my node.js app that is returning JSON data for computers. { computers: { john: { cpu: "intel", ram: "8MB", hd: "1TB" }, jane: { cpu: "intel", ram: "12MB", hd: "500GB" }, mary: { ...

Best approach to inform pages about a variable update in Ionic

Imagine a scenario where we have a page called ListItemPage displaying a list of items: Within the ts file, there is a variable defined as items: any = []; In the html file, we find <ion-item *ngFor="let item of items"> Users can click on a (+ ...

Avoid including any null or undefined values within a JSON object in order to successfully utilize the Object.keys function

My JSON data structure appears as follows: { 'total_count': 6, 'incomplete_results': false, 'items': [ { 'url': 'https://api.github.com/repos/Samhot/GenIHM/issues/2', 'repository_url' ...

The array_unique function does not organize values that are from a regular expression

I've been working with a regex and counting matches, but now I want to focus on unique matches. Surprisingly, using array_unique() isn't doing the trick. preg_match_all("/".$toArray."/i", $input, $matches); $count_matches = count($matches[0]); ...

Eliminating attributes in mapStateToProps

When wrapping material TextField with a redux component, it is important to consider that some properties should be used in mapStateToProps only and not passed directly to the component. Otherwise, an Unknown prop warning may occur. Even specifying an unde ...

Ways to prompt a specific text value to generate varied responses

Whenever I try to input the letter "h", I expect a specific value in return but for some reason, it's not working as intended. Despite my best efforts to troubleshoot the issue, I have been unsuccessful in finding a solution. It's frustrating bec ...

Are Java's arrayLists a hybrid of arrays and lists?

During a recent project for school, I had the opportunity to work with arrayLists in Java. This got me thinking - is an arrayList considered as just an array, a list, or perhaps both? ...

Obtain the date in the following format: 2016-01-01T00:00:00.000-00:00

Can someone help me convert this date to the correct format for the mercadolibre api? I need it to be like this: 2016-01-01T00:00:00.000-00:00 However, when I try with the following code: var date_from = new Date(); date_from.setDate(date_from.getDa ...

What is the best way to close all other accordion tabs when selecting one?

A simple HTML code was created with the full pen accessible here. <div class="center"> <div class="menu"> <div class="item"> <button class="accordionBtn"><i class=&q ...

Can you provide guidance on integrating this jQuery script into my Next.Js application effectively?

I have been using a script on a plain HTML website, importing it via the <script> tag: (function($) { var wa_time_out, wa_time_in; $(document).ready(function() { $(".wa__btn_popup").on("click", function() { if ($(&qu ...

Receiving the most recent data in a protractor examination as a text string

My goal is to fetch an input value for a specific operation in protractor. I am attempting to make an ajax request using protractor and need to assign a unique value (referred to as groupCode) to a JSON object that will be sent to the server. Initially, I ...

Navigate to the following input field upon a keyup event occurring within the table

I have a table that contains multiple input fields in a single row within a td element. I am trying to implement functionality that will automatically shift focus to the next input field when any number is entered. The code works perfectly without the tabl ...

What are the steps to create a custom progress bar using JavaScript?

I have experience with HTML and CSS. Below is the HTML code: <div id="wrapper"> <ul id="top"> <center><li><a href="#one" class="button">GENERATE</a></li></center> </ul> <div class="box" i ...

Issue encountered: The differ cannot recognize the provided object '[object Object]', which is of type 'object'. NgFor is limited to binding Iterables only

I have been following a tutorial on Ionic created by Paul Halliday, focusing on a shopping list project that utilizes Firebase and Angular. However, I am encountering an error every time I try to run the application: Error: Uncaught (in promise): Error: ...

Why would someone opt to utilize process.env.PORT in their code?

Setting the environment variable PORT to a specific value, such as set PORT=5000, provides explicit instructions on which port the program should use. How does this method differ from simply instructing it to use port 3000? ...

Executing a JavaScript Function in the Background using Cordova

Despite the numerous questions and plugins available on this topic, finding a solution has proven to be elusive for me. The most highly recommended plugin for this issue can be found here. My goal is to run MyService in the background, subscribe to the ON ...

Switch Button Hyperlink in HTML/CSS

I have the following code: document.addEventListener("DOMContentLoaded", function(event) { (function() { requestAnimationFrame(function() { var banner; banner = document.querySelector('.exponea-banner3'); banner.classList ...