Mohamed Rihan
Mohamed Rihan

Reputation: 119

How to map an Array of arrays to object like property and value?

Im new to javaScript and react..

i have an array consisting of objects. I need to display this array in a AG GRID so what im tring here to map this to array of flat obj.

NOTE: I cannot use jQuery..

below is my array (full code is in codepen, please check the link)

let realData = [
  [
    {
      "key" : "flightNumber" ,
      "label": "Flight Number",
      "value": "EK 131",
      "value-type": "String",
      "order" : 1
    },
    {        
      "key" : "flightId",
      "label": "flightId",
      "value": "1223434",
      "value-type": "String",
      "order" : 2,
      "isId": true
    },
    {

      "key": "CallSign",
      "label": "callSign",
      "value": "123",
      "value-type": "String",
      "order" : 3
    },
  ]
]

what i want the result is

let newArray = [
    {flightNumber: 'EK 131', flightType: 'A', lastUpdate: '11223232', destOrig: 'BEY', sibtSobt: '12121333123', CallSign: '123'},
    {flightNumber: 'EK 132', flightType: 'D', lastUpdate: '11334455', destOrig: 'DEST', sibtSobt: '1234443222', CallSign: '443'}
]

please help

link

Thank you

Upvotes: 0

Views: 6362

Answers (3)

Shrey Kejriwal
Shrey Kejriwal

Reputation: 736

Check the below working code...

const newData = [];

realData.forEach((val) => {
  let obj = {};
  val.forEach(v => obj[v.key] = v.value);
  newData.push(obj);
});

console.log(newData);

Upvotes: 3

Gabriel Bleu
Gabriel Bleu

Reputation: 10192

You can reduce each array key/value pair into an object :

const arrays = [
[
    {
      "key" : "flightNumber" ,
      "label": "Flight Number",
      "value": "EK 131",
      "value-type": "String",
      "order" : 1
    },
    {        
      "key" : "flightId",
      "label": "flightId",
      "value": "1223434",
      "value-type": "String",
      "order" : 2,
      "isId": true
    },
    {

      "key": "CallSign",
      "label": "callSign",
      "value": "123",
      "value-type": "String",
      "order" : 3
    }
]
];

const objects = arrays.map(arr => arr.reduce((acc, cur, i) => {
  acc[cur.key] = cur.value;
  return acc;
}, {}));

console.log(objects);

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386522

You could map the new objects with Object.assign for a single object.

var data = [[{ key: "flightNumber", label: "Flight Number", value: "EK 131", "value-type": "String", order: 1 }, { key: "flightId", label: "flightId", value: "1223434", "value-type": "String", order: 2, isId: true }, { key: "CallSign", label: "callSign", value: "123", "value-type": "String", order: 3 }]],
    result = data.map(a => Object.assign(...a.map(({ key, value }) => ({ [key]: value }))));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 3

Related Questions