I have this simple array:
const arr = [
{
"id": 2,
"color": "red"
},
{
"id": 1,
"color": "blue"
},
{
"id": 2,
"color": "yellow"
},
];
I want to create a hash map where I want to add new colors on that key.
E.g I want to added color: green
on id: 3
Now here you can see there is no id: 3
Now here I am expecting:
{
2: [{color: "red"}]
1: [{color: "blue"}, {color: "yellow"}],
3: [{color: "green"}]
}
Now if I want to add color: brown
on id: 2
In that case I am expecting:
{
2: [{color: "red"}, {color: "brown"}]
1: [{color: "blue"}, {color: "yellow"}],
3: [{color: "green"}]
}
I have created a Playground:
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"}]))
Here I also want to avoid duplicates