-1

Can anyone help me or give me sample/example for javascript code like what I explained?

I have array like this

    var obj = [ 
        {rgb : 'val1', x : '10', y : '15'}, 
        {rgb : 'val1', x : '20', y : '25'},  
        {rgb : 'val1', x : '30', y : '35'} 
    ];

I want array like this way

    var obj = { 
        'val1' : [ {x : '10', y : '15'}, {x : '20', y : '25'},  {x : '30', y : '35'} ] 
    };
cbayram
  • 2,259
  • 11
  • 9

2 Answers2

1

Something like this:

var newObj={};
for(var i=0, l = obj.length; i<l; i++){
  if (typeof newObj[obj[i].rgb] === 'undefined')
    newObj[obj[i].rgb] = []; 
  newObj[obj[i].rgb].push({ x: obj[i].x, y: obj[i].y })
}
obj = newObj;
Malk
  • 11,855
  • 4
  • 33
  • 32
0

What you are going to want to do to have a 'map' type structure is this:

var obj = {
   'val1': [{x : '10'},{y : '10'}]
} 
Carlos Pliego
  • 859
  • 1
  • 8
  • 19