mm1975
mm1975

Reputation: 1655

Add new keys and values in a array

I have an array which has multiple keys name and different keys for abteilung:

{abteilung: "Research & Development", name: "Susanne Gast"}, {abteilung: "HR", name: "John Doe"}, {abteilung: "HR", name: "Joe Doe"}...

Now I want to add a key target with a unique id for every name. And I also want to add a key source with an id for every key+value abteilung. There are duplicates for abteilung.

I'm able to add the key+value target. But how can I add the key+value for abteilung

let linksArray = links;
let u = 0, let a = 0, ln = linksArray.length;       
for (u;u<ln;u++){   
   linksArray[u].target = u+1;
}

Thank your for your hints

Upvotes: 0

Views: 51

Answers (1)

trincot
trincot

Reputation: 350137

For assigning the source, you could first build a Map that has a key for every unique abteilung. The Map values can then become the sequential number. Finally perform a look-up in that Map for each object and assign the retrieved number to the source property:

const links = [{abteilung: "Research & Development", name: "Susanne Gast"}, {abteilung: "HR", name: "John Doe"}, {abteilung: "HR", name: "Joe Doe"}];

const map = new Map(links.map(o => [o.abteilung, 0]));
Array.from(map.keys(), (abteilung, i) => map.set(abteilung, i+1));
links.forEach(o => o.source = map.get(o.abteilung));
console.log(links);

I did not include the assignment to target, as you had that working fine already.

If it is not necessary that the numbering is a sequence without gapes, but gaps are allowed, then you can also assign the sequence number during the Map construction:

var links = [{abteilung: "Research & Development", name: "Susanne Gast"}, {abteilung: "HR", name: "John Doe"}, {abteilung: "HR", name: "Joe Doe"}];

let i = 0;
const map = new Map(links.map(o => [o.abteilung, i++]));
links.forEach(o => o.source = map.get(o.abteilung));
console.log(links);

Upvotes: 1

Related Questions