PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 20, 2022

[FIXED] how to get unique properties from object <Map>

 September 20, 2022     arrays, hashmap, javascript, object, typescript     No comments   

Issue

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'


Solution

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);



Answered By - trincot
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing