Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get individual key value from “Set” Object in JavaScript?

I have Set() object with three key value

var myset =new Set();
myset.add('first','This is first value');
myset.add('second','This is second value');
myset.add('third','This is third value');

Using loop I can got value of these three key

for( var value of myset){
  console.log(value);
}

How can get individual value? I want to get second key of value?

Is there any option?

I have tried these but not working

myset.get('second');
myset(1);

var myset = new Set();
myset.add('first', 'This is first value');
myset.add('second', 'This is second value');
myset.add('third', 'This is third value');

//   Using loop I can got value of these three key

for (var value of myset) {
  console.log(value);
}

// How can get individual value? I want to get second key of value?

// I have tried these but not working

myset.get('second');
myset(1);
like image 765
Jitendra Suthar Avatar asked Dec 23 '22 05:12

Jitendra Suthar


1 Answers

Set is a set of values, not a map of them, so add accepts 1 argument, which is a value. The thing you're looking for is Map.

Getting a value by its index is explained in this answer and it's same for both Set and Map. A collection should be iterated until the index is reached. This can be done in less efficient manner by converting it to an array first:

const map = new Map();
map.set('first','This is first value');
map.set('second','This is second value');
map.set('third','This is third value');

console.log(map.get('second') === 'This is second value'); // true
console.log([...map.values()][1] === 'This is second value'); // true
like image 199
Estus Flask Avatar answered Dec 25 '22 23:12

Estus Flask