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