-1

I am not able to convert the below object, I have to convert the below object :

var words = [{
 IBM: '00AJ136',
 DESCRIPTION_IBM: '500GB Serial ATA (SATA) 2.5"" 6G 7.2K NL SFF G3HS Hot-Swap Hard Drive',
 HP: '332751-B21',
 DESCRIPTION_HP: 'Compaq 72GB Non-Hot Plug Ultra320 SCSI Hard Drive 10K',
 DELL: '01XF66',
 DESCRIPTION_DELL: 'DELL 1.2TB HARD DRIVE',
 HITACHI: 'HUC101890CSS204',
 DESCRIPTION_HITACHI: '900GB 10K 12G SAS HARD DRIVE',
 EMC: '5048946',
 DESCRIPTION_EMC: '005048946 EMC 300GB 10K SFF SAS HARD DRIVE',
 SEAGATE: '2C6200-002',
 DESCRIPTION_SEAGATE: '2C6200-002  SEAGATE 300GB 10K SFF SAS HARD DRIVE',
 WD: 'WD1000CHTZ',
 DESCRIPTION_WD: 'WD 1TB 7200 6G 2.5"" SATA DRIVE',
 TOSHIBA: 'DT01ACA300',
 DESCRIPTION_TOSHIBA: 'TOSHIBA DT01ACA300 3TB 7200rpm 3.5"" Serial ATA 3.0 Hard Drive'
}]

into this :

{ 
  00AJ136: "500GB Serial ATA (SATA) 2.5"" 6G 7.2K NL SFF G3HS Hot-Swap Hard Drive",
  332751-B21 : "Compaq 72GB Non-Hot Plug Ultra320 SCSI Hard Drive 10K",
  .
  .
  .
  & so on 
}

Can any please help me on how to approach this scenario. Thanks in advance.

vipin joshi
  • 47
  • 1
  • 9
  • 1
    `words` is an array. This array is expected to have single object always? – Vivek Bani May 30 '21 at 11:17
  • Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available [`Object`](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods) methods (both static and on prototype). – Sebastian Simon May 30 '21 at 11:18

2 Answers2

2

based on your code above, you can achieve this by using this code:

var oNew = {};
   $.each(words[0], function(key, value) {
      if(key.match('DESCRIPTION') === null) {
          oNew[value] = words[0]['DESCRIPTION_' + key];
      }
  });

Good luck :)

partik
  • 23
  • 5
0

Assuming the array word will have single object

let obj = {};

Object.entries(words[0]).forEach(([k,v]) => obj[k] = v);

console.log(obj)

if the array word has more than 1 items then,

let result = words.map(w => { 
                            let obj = {}; 
                            Object.entries(w).forEach(([k,v]) => obj[k] = v); 
                            return obj;
                        });

console.log(result);
Vivek Bani
  • 3,703
  • 1
  • 9
  • 18