7

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

3

5 Answers 5

7

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

Sign up to request clarification or add additional context in comments.

5 Comments

NB: [...map.values()][1] is a way of accessing the second element inserted in a Map, but only because it's implemented that way in Javascript. Maps and map-like data structures (like Object) in JS and other languages do not guarantee insertion order.
@BrDaHa Actually, ES6 Map guarantees the order, this is the way it differs from object literal, apart from non-string keys. Can't say for other languages.
Yes, I mentioned that :)
@BrDaHa My point was it's more than an implementation, this behaviour is strictly specified. On the other hand, object literals are implemented in all modern engines to maintain the order too, but specs don't guarantee that.
I didn't know it was in the spec, that's nice. I was simply cautioning the user against relying on it as a consistent property of hashed collection data structures in other programming languages.
2

Javascript Set.add() only takes one parameter. So your second param is always ignored, and as its JS this doesnt throw any error. You can achieve what you are trying using simple JS object.

var x = {}
x[key1] = value1
x[key2] = value2

And then you can get the values like:

x[key1] # will output value1

Comments

2

You're using a Set wrong. It's not a key/value store, but a list of unique values.

Source

Your code...

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

Is really creating a set with values "first", "second", "third" (the second argument is ignored, since Set.prototype.add() only takes one argument).

For a generic key/value store, you should use either a Map or a regular JavaScript object (depending on your supported environment).

Map

A map lets you store key/value pairs where the key can be any type. This is different to a regular JS object where the key must be of string type.

const myMap = new Map();
myMap.set('key', 'value');

Regular JS Object

You can use a regular JS object, since your keys are strings, preferably with a null prototype available via Object.create(null) (the null prototype ensures you won't read any other values back on the prototype chain without having to do a Object.prototype.hasOwnProperty() check).

3 Comments

This answer should be suggesting Map syntax
@BrDaHa updated - would you recommend using Map always, even if the keys are strings, like in the OP's example?
Yes, it's typically more performant and more intuitive for usages such as the OP's (in terms of access and iteration, maybe less so in terms of serialization)
0

Set.add only take one parameter. What you can do is, Insert JSON object instead shown as below:

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

var val = [...myset].filter(x => x.hasOwnProperty('first'))[0]['first'];
console.log(val)

3 Comments

And if you create one with (null) you might not have to test for ownproperty
Yes, that kind of validation must be there obviously. I have tried to answer as per OP code (Positive test case)
This is the wrong way to use a Set. If you add a fourth line exactly like the third, you will still have 4 unique elements in the Set because {'third':'This is third value'} !== {'third':'This is third value'}
0

Because the Set object is implemented as a generator is not possible to get its values by index straight away, although there are two options to achieve this.

1.- Unpack the Set generator and retrieve the value by index.

function list(setobj) {
    var result = []
    for (var value of setobj){
       result.push(value)
    }
    return result
}
asd = new Set([1,2,3,3,4,4])
list(asd.values())[1] 
// 2

2.-Implement your own Set subclassing Array

function set(){
    var args = arguments
    if (arguments[0] instanceof Array) {
        args = arguments[0]
    }
    for (var index in args){
        self.add(args[index])
    }
}
set.prototype = new Array
set.prototype.add = function (el) {
    if (this.indexOf(el) == -1) this.push(el)
}
asd = new set(1,1,1,2,2,3)
console.log(asd[1])
// 2
asd = new set([1,1,1,2,2,3])
console.log(asd[1])
// 2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.