0

I'm looking for elegant way to implement unique key value set in javascript,

I have an object that looks like the following:

{
    "name" : "admin",
    "type" : "users",
    "id" : "53cf50b32508adc39b0cc566"
},
{
    "name" : "admin2",
    "type" : "users",
    "id" : "53cf50b32508adc39b0cc566"
}

i want to create array / set that will have id as the key and name,type as the values.

the set must be unique!

the result should by

array : [53cf50b32508adc39b0cc566 : {"name" : "admin2","type" : "users"}]

the id should appear only once

any suggestions?

Liad Livnat
  • 7,435
  • 16
  • 60
  • 98

2 Answers2

1

The mistake you're making is that you want to have an data structure that's not permitted in JavaScript:

array: [53cf50b32508adc39b0cc566 : {"name" : "admin2","type" : "users"}]

The above line makes no sense and will cause an error.

Assuming that you want to access your data by key, and your current data is in an array, all you need to do is create a new object and then loop over the parsed JSON, adding each object as a value to a new key id.

var out = {};
for (var i = 0, l = arr.length; i < l; i++) {
  out[arr[i].id] = {
    name: arr[i].name,
    type: arr[i].type
  };
}

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95
  • well i'm want a code that iterate the json and result in an array of this kind of object this was the meaning, i need it to be unique – Liad Livnat Jul 23 '14 at 09:47
  • @LiadLivnat note you should have included all the relevant information in your question the first time round. – Andy Jul 23 '14 at 10:01
0

You can use something like that :

    var person = new Object();

var uid = createGuid();

person[uid] = { name : "admin" };


console.log(person);

    function createGuid(){
            var g = "0123456789abcdef".split("");
            var e = [];
            var h;
            for (var f = 0; f < 32; f++) {
                h = Math.floor(Math.random() * 16);
                if (f == 16) {
                    e[f] = g[(h & 3) | 8]
                } else {
                    e[f] = g[h]
                }
            }
            e[12] = "4";
            return e.join("")
        }
Muhammet Arslan
  • 975
  • 1
  • 9
  • 33
  • sorry this is not what i mean, i need a unique list, not of guids, but go over an existing array and create unique list out of it. – Liad Livnat Jul 23 '14 at 09:48
  • `var a = [],person = new Object(); person = { name : "admin",type:"admin",id:"545421fdsfvdb" }; var id = person.id; a[id] = []; delete person.id a[id].push(person); console.log(a) ;` is it ? – Muhammet Arslan Jul 23 '14 at 09:56