Home > Blockchain >  how to get unique properties from object <Map>
how to get unique properties from object <Map>

Time:07-16

I have a and Map with one Object that contains a list of arrays. For example:

Map(1) {'SAMSUNG' => Array(5)}
  [[Entries]]
    0: {"SAMSUNG" => Array(5)}
      key: "SAMSUNG"
      value: Array(5)
        0: {externalKey: '0001', brand: 'V', country: 'DE', deviceType: 'TSU4'}
        1: {externalKey: '0002', brand: 'V', country: 'FR', deviceType: 'TSU1'}
        2: {externalKey: '0005', brand: 'N', country: 'DE', deviceType: 'TSU4'}
        3: {externalKey: '0008', brand: 'V', country: 'AB', deviceType: 'TCU4'}
        4: {externalKey: '0009', brand: 'G', country: 'DE', deviceType: 'TCU7'}
        length: 5
        [[Prototype]]: Array(0)
        size: 1
        [[Prototype]]: Map

I like to know how I can get the unique brand country and devicetype , eg: brand['V','N','G'].

First I need to know how to access this map value Array of 5 values.

I tried something like this:

Object.keys(myObj)

But it gives me 'undefined'

CodePudding user response:

Your map has one key "SAMSUNG", and you can get its contents with mymap.get("SAMSUNG"). That will be an array in this case.

Here is an example on how that map could have been built, how you can get access to the array, and how you could group countries by brand (just as example):

// Create the map (you already have it -- so you wouldn't do this)
const map = new Map().set("SAMSUNG", [
    {externalKey: '0001', brand: 'V', country: 'DE', deviceType: 'TSU4'},
    {externalKey: '0002', brand: 'V', country: 'FR', deviceType: 'TSU1'},
    {externalKey: '0005', brand: 'N', country: 'DE', deviceType: 'TSU4'},
    {externalKey: '0008', brand: 'V', country: 'AB', deviceType: 'TCU4'}, 
    {externalKey: '0009', brand: 'G', country: 'DE', deviceType: 'TCU7'}
]);

// Get access to the array
const arr = map.get("SAMSUNG");

// Example: group countries by brand
const groups = {};
for (const {brand, country} of arr) (groups[brand] ??= []).push(country);
console.log(groups);

  • Related