Sunil Lama
Sunil Lama

Reputation: 4539

Convert array into object with custom key

I have an array:

let Given = [
  ["SRM_SaaS_ES,MXASSETInterface,AddChange,EN"],
  ["ASSETNUM,AS_SITEID,apple,ball"],
  ["mesa01,SDASITE,ball,cat"],
  ["ASSETNUM,AS_SITEID,cat,ager"]
];  

What i want is get the first array as keys and the rest as its respective values as follows:

let needed = [{
    'SRM_SaaS_ES': 'ASSETNUM',
    'MXASSETInterface': 'AS_SITEID',
    'AddChange': 'apple',
    'EN': 'ball',
  },
  {
    'SRM_SaaS_ES': 'mesa01',
    'MXASSETInterface': 'SDASITE',
    'AddChange': 'ball',
    'EN': 'cat',
  },
  {
    'SRM_SaaS_ES': 'ASSETNUM',
    'MXASSETInterface': 'AS_SITEID',
    'AddChange': 'cat',
    'EN': 'ager',
  }
]

What i tried to do was get the first array and then assign the values to the first array as keys but i couldn't.

let firstArrayData: string = this.Given[0];
let data = firstArrayData[0].split(',');
console.log(JSON.stringify(data));//["SRM_SaaS_ES","MXASSETInterface","AddChange","EN"]

Upvotes: 0

Views: 859

Answers (1)

nnnnnn
nnnnnn

Reputation: 150040

Here's one way to do it:

let Given = [
  ["SRM_SaaS_ES,MXASSETInterface,AddChange,EN"],
  ["ASSETNUM,AS_SITEID,apple,ball"],
  ["mesa01,SDASITE,ball,cat"],
  ["ASSETNUM,AS_SITEID,cat,ager"]
];

// first get the keys out of the first sub array:
const keys = Given[0][0].split(",");

// then map over the rest of the sub arrays:
const result = Given.slice(1).map(function(item) {
  // get values from current item
  const values = item[0].split(",");
  // create an object with key names and item values:
  const obj = {};
  keys.forEach(function(k,i) {
    obj[k] = values[i];
  });
  return obj;
});

console.log(result);

Upvotes: 2

Related Questions